Button with three state images

Description

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>//from   w w  w.j  av  a2s  . co  m

Note

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 /res/drawables folder.

In the definition of your button in the layout XML file, set the android:src property to the selector XML file as if it were a regular drawable.


<Button   ...    android:src="@drawable/imagebuttonselector"    ...   />




















Home »
  Android »
    Android UI »




UI Basics
Action Bar
Animation
Button
Canvas
CheckBox
Clock Date Picker
Dialog
EditText
Event
Fragment
Gesture
GridView
ImageView
Layout
ListView
Map
Menu
Model
OpenGL
ProgressBar
RadioButton
Spinner
Tab
TextView
Thread
Toast
Video
View
WebView