Android Button Selector tutorial with example


               Android button can be set to display image as background. We can go beyond just displaying image, where Android allows us to differentiate different states of the selected button. This tutorial focuses on this concept, wherein we will display different images for button states - normal, focused and pressed.

              This will be very simple since  <Selector> will handle all the stuff. Lets see this tutorial step by step that will provide a clear understanding.

1. Create activity_main.xml
              In your main activity add a button as shown below :


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
android:orientation="vertical" >

android:background="@drawable/selector_button" />


2. Prepare three images to differentiate button states

Focused - Display when button is focused using keypad etc.,
Normal - When button is left idle
Pressed - Display when button is pressed

3. Add Selector for button
            This is the important part of this tutorial, wherein you need to create a new XML file under drawable folder as shown below :

This file contains <Selector> code that will decide what image to display on various button states


<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="">
<item android:drawable="@drawable/pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/focused"
android:state_focused="true" />
<item android:drawable="@drawable/normal" />

This xml file needs to be set as background to Android:button

 android:background="@drawable/selector_button" />

4. Add button listener in Code

             In your add a button listener and on the initial display I have set button focus and hence it will display Grey image on initial run. Rest states are based on our activity.

Done.. ? Just run the application, you can see the below output.

package com.example.imagebutton_android;

import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

Button imageButton;
Button imageButton1;

public void onCreate(Bundle savedInstanceState) {
imageButton1 = (Button) findViewById(;

public void addListenerOnButton() {

imageButton = (Button) findViewById(;
imageButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(MainActivity.this, "Button clicked!",




Source Code of this Application

No comments:
Write comments

Popular Posts