Thursday, January 10, 2013

How to make custom drawable background depending on clicked states in Android

This post targets to use different images for the clickable views like buttons, checkboxes etc for their different states.

States can be:

  1. Normal
  2. clicked 
  3. focused
  4. disabled
  5. normal after clicked (in case of radio button)
For this you would require separate images for every state.
Place them in res folder.

Create a new xml, say my_button_bg.xml
Content of it will be like:

<?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:state_hovered="true"
          android:drawable="@drawable/button_focused" /> <!-- hovered -->
    <item android:drawable="@drawable/button_normal" /> <!-- default -->
</selector>


What can be the different states of any view, is :

        android:state_pressed=["true" | "false"]
        android:state_focused=["true" | "false"]
        android:state_hovered=["true" | "false"]
        android:state_selected=["true" | "false"]
        android:state_checkable=["true" | "false"]
        android:state_checked=["true" | "false"]
        android:state_enabled=["true" | "false"]
        android:state_activated=["true" | "false"]
        android:state_window_focused=["true" | "false"] />


So the idea is, depending upon the states mentioned above you can choose the image you want to show on that state and place that entry in the file mentioned just above this list.

In your activity layout file, add this xml file as the background of your view:
   android:background="@drawable/my_button_bg"

At the run time, android will pick the image as you mentioned depending upon the state you mentioned and will show on the screen.

**NOTE : Try to add the state entry to your xml file in the same order as mentioned in the above list for minimal complications.


No comments:

Post a Comment