- Sometimes you may need to change the background of an item as soon as its state changes. For example, if there is an ImageButton having a particular image on it. If you click the ImageButton, it will show no changes in itself and will merely do the tasks that you want it to do. But if you want your ImageButton to change its image for a while when it is clicked and then come to normal state, you can use a separate feature for it.
- In this feature, you get different drawable not only for click event but you may define drawalbes for many more drawables. Here is the procedure.
Step 1- You have to create a new xml file as the states and their drawables will be defined in this xml file and this xml file will be used as background. Create this xml file in any ‘drawable’ folder inside ‘res’ folder. To create an xml file in drawable folder, right click on the drawable folder and then go to New->Other…
- You will see following dialog box. Choose XML File from the category XML and click Next. Now give a desired name to the file and click Finish. We have named it ‘mybackground.xml’.
Step 2- Open the file and create a tag selector in it as following.<?xml version=”1.0″ encoding=”UTF-8″?>
Step 3- Now inside this tag you can define your drawables for different states. To do this, item tag is used. We are creating a drawable for the click state in following code.<selector xmlns:android=”http://schemas.android.com/apk/res/android”>
- First item defines a drawable for the state when the view is clicked or pressed. The second item defines the default drawable for that view i.e. when the view is in normal state, this drawable will be in effect.
- Note: The item which defines the default drawable for the view must be written at the end otherwise the item that will be written after it will be of no use.
- Step 4- Use this xml file as the value of background attribute of the view for which you want to set it.
There are many states available. You can see all of them by pressing Ctrl+Space inside the opening item tag. Some states are described here-
- android:state_focus = When a view has input focus.
- android:state_window_focus = When a view’s window has input focus.
- android:state_enabled = When a view is enabled.
- android:state_checkable = When a view can be checked.
- android:state_checked = When a view is checked.
- android:state_selected = When a view is selected.
- android:state_pressed = When a view is pressed or clicked.
- android:state_activated = When a view is activated.