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=”http://schemas.android.com/apk/res/android” >

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

          android:state_pressed=”true” />

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

</selector>

 

Code in layout  file :

Here, we set selector as the background of the button

 <Button

            android:id=“@+id/b1”

            android:layout_width=“wrap_content”

            android:layout_height=“wrap_content”

            android:background=“@drawable/selector”

            android:text=“1”

            />

  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(R.id.button_id);

StateListDrawable state = new StateListDrawable();

state = new StateListDrawable();

//add new image resource for a specific state

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

                                        getResources().getDrawable(R.drawable.btn_up_cyan));

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

                                        getResources().getDrawable(R.drawable.btn_up_cyan));

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

 

 

Hope this post is helpful . 🙂