Android lets you  change the button’s image at runtime depending on it’s states like s focused or pressed.

This is achieved using selectors .The selector  xml is created in drawable folder ,which is a sub folder of res folder. In this example when the button is pressed the background image changes.

 The selector.xml is given bellow

 <?xml version=”1.0″ encoding=”utf-8″?>

<selector xmlns:android=”” >

    <item android:drawable=”@drawable/ok_pressed”

          android:state_pressed=”true” />

    <item android:drawable=”@drawable/ok”  />



Code in layout  file :

Here, we set selector as the background of the button








  Also, we can dynamically replace selector images  in the following manner.

StateListDrawable -Lets you assign a number of graphic images to a single Drawable and swap out the visible item by a string ID value.


Button button=(button) findViewById(;

StateListDrawable state = new StateListDrawable();

state = new StateListDrawable();

//add new image resource for a specific state

state.addState(new int[] {android.R.attr.state_pressed},


                                    state.addState(new int[] {android.R.attr.state_focused},


    button.setBackgroundDrawable(state);//set the background of button according to ‘state’



Hope this post is helpful . 🙂