We can set image to a button in state of pressed, focused and normal by using a selector.
The selector is a simple XML file that resides in the /res/drawable folder.
The content of a selector file will look like the following.
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_pressed="true" android:drawable="@drawable/button_pressed" /> <!-- pressed --> <item android:state_focused="true" android:drawable="@drawable/button_focused" /> <!-- focused --> <item android:drawable="@drawable/icon" /> <!-- default --> </selector>
First, you do not specify a
<resources> tag as in values XML files.
The order of the button images is important. Android will test each item in the selector, in order, to see if it matches.
The normal image should be last so it is used only if the button is not pressed and if the button does not have focus.
If the normal image was listed first, it would always match and be selected even if the button is pressed or has focus.
The drawables you refer to must exist in the
In the definition of your button in the layout XML file,
to the selector XML file as if it were a regular drawable.
<Button ... android:src="@drawable/imagebuttonselector" ... />