Learn Android Development For Beginners

Button Controls

Buttons are also common control to build user interface. The Android provides the following types of button controls.

  1. Button
  2. Image Button
  3. Toggle Button

1. Button

The button control is a common control to design user interface. Button controls require to handle the click event when user touch the control on screen. It also has properties for background color, font styles and alignment etc. These properties are also same for the other controls available in Android.

While designing UI using designer the control palette shows two types of buttons Button and Small Button.

Button and Small Button both use <button> element in layout file. The only difference is the Style attribute of the button. For small button it sets the style attribute as style="?android:attr/buttonStyleSmall".

 <button android:id="@+id/button1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Simple Button"
                android:layout_margin="4dp"
                android:layout_gravity="center_horizontal"
                android:onclick="buttonClickHandler" />
 <button android:id="@+id/buttonSmall"
                style="?android:attr/buttonStyleSmall"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Small Button"
                android:layout_gravity="center_horizontal"
                android:onclick="buttonClickHandler" />

Run the application and the screen shows two button one has small in font size and other is normal in size. The Text property is use for showing content on the button e.g. android:text="Simple Button" shows “Simple Button” text on the first button.

Android provide different ways to handle click event. It also provides a way to set event handler using android:onClick property. The android:onClick="buttonClickHandler" means there should be a public method buttonClickHandler available in the code file otherwise the application will throw exception when user click on button. In the code below there is a method buttonClickHandler to handle click event of the button.

 public void buttonClickHandler(View v) {
 
    String message = "";
 
   if(v.getId() == R.id.button1)
   {
       message = "Clicked on Button 1";
   }
   else if(v.getId() == R.id.buttonSmall)
   {
       message = "Clicked on small Button";
   }
  
   Toast.makeText( getApplicationContext(), message,
                Toast.LENGTH_SHORT ).show();
 }

In this method user gets the instance of click control in View class. The getId() method returns the integer id of the click element.

Android also provide a way to register click handler of the button form code file. Get the button using findViewById() method and set its properties and event listener from code file.

 Button btn1 = (Button)findViewById(R.id.button2);
 btn1.setOnClickListener(new View.OnClickListener() {
      
      @Override
      public void onClick(View view) {
            Toast.makeText(getApplicationContext(),"Clicked on Button 2.", 
                           Toast.LENGTH_SHORT).show();
      }
 });

Register the click handler by calling setOnClickListener method with View.OnClickListener and create the anonymous method on fly for click listener.

You can read more about click event handler on the blog How to handle events in Android

Show image with text

Button also provides a way to set image with text by using drawable properties

drawableLeft, drawableRight, drawableBottom, and drawableTop properties are used for positioning the image with the text. It also provides the drawablePadding to set the padding to image.

Add new button and set its drawableLeft and drawablePadding property. See the sample xml below

 <button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"
        android:layout_margin="4dp"
        android:layout_gravity="center_horizontal"
        android:drawableleft="@drawable/save"
        android:drawablepadding="10dp" />

2. Image Button

The use image button is same as the normal button control except it provides “src” property to show image in the button. <imagebutton> element is use to add button in the layout.

 <imagebutton android:id="@+id/imageButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_margin="4dp"
            android:src="@drawable/save"
            android:onclick="buttonClickHandler" />

The registering of the click event of the ImageButton is same as the normal button. It can be set using onClick property or registering click listener in code file.

ImageButton image can also be set from the code file. See the code below to set image and register click listener.

 ImageButton btn = (ImageButton)findViewById(R.id.imageButton2);
 
 btn.setImageResource(R.drawable.save);
 btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Toast.makeText(getApplicationContext(),"Clicked on Image Button 2.", 
                        Toast.LENGTH_SHORT).show();
    }
 });

For setting image from the code file use setImageResource method of the image button instance and the registering click listener is same as Button.

3. Toggle Button

The toggle button is two state button like a check box or radio button. It has two state either on or off. It exposes different properties to set text for on and off states using android:textOn and android:textOff properties.

 <togglebutton android:id="@+id/toggleButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New ToggleButton"
            android:layout_gravity="center_horizontal"
            android:layout_margin="4dp"
            android:onclick="buttonClickHandler"
            android:textoff="Normal"
            android:texton="Pressed"
            android:checked="true" />

The text property of the Toggle button has no use because it has 2 separate properties for on and off status. The click event registration is also same as Button control.

The checked property is use to set the current state of the button. android:checked="true" set the On state of the button.

From code file, Android provides methods to set on and off text and get/set the current state of the button.

 ToggleButton btn = (ToggleButton)findViewById(R.id.toggleButton2);
 
 btn.setTextOff("Normal");
 
 btn.setTextOn("Press");
 
 btn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        ToggleButton button = (ToggleButton)view;
        String status = button.isChecked()? "Presses":"Normal";
        String message = "Clicked on Toggle Button. Current status = " + status ;
        Toast.makeText(getApplicationContext(),message, Toast.LENGTH_SHORT).show();
    }
 });

setTextOff() method sets the off state text and setTextOn() method sets the on state text. isChecked() method returns the current state of the toggle button.

Set background image for Different Button states

Android also proved a way to change style or image for different states of the button. In this section you will learn how to change background image for the different states of the buttons. Put all the images for different button state in the drawable folder. As you can see image below.

For setting states add new xml file in the drawable folder and name it button_style or any other. Add the following xml in the file.

 <selector xmlns:android="http://schemas.android.com/apk/res/android">
   
    <item android:drawable="@drawable/button_clicked" 
            android:state_selected="true"></item>
    
    <item android:drawable="@drawable/button_pressed" 
             android:state_pressed="true"></item>
    
    <item android:drawable="@drawable/button_normal"></item>
 
 </selector>

It is the single drawable resource which change the image based on the current state of the button. <item> element present image as per its state setting. State can be android:state_selected, android:state_pressed, and android:state_focused etc.

Now add button in to the layout and set xml drawable resource to the background property of the button android:background="@drawable/button_style".

 <button android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:text="Click!"
         android:layout_margin="4dp"
         android:layout_gravity="center_horizontal"
         android:background="@drawable/button_style" />

Execute the application and notice that background changes based on current state of the button.

  

Download Source Code

You can get the source code. Download Source Code

;