In this section, you will create a button with a custom image instead of text, using the Button widget and an XML file that defines three different images to use for the different button states. When the button is pressed, a short message will be displayed.
Copy the images on the right into the res/drawable/ directory of your project. These will be used for the different button states.
Create a new file in the res/drawable/ directory named android_button.xml. Insert the following XML:
This defines a single drawable resource, which will change its image based on the current state of the button. The first <item> definesandroid_pressed.png as the image when the button is pressed (it's been activated); the second <item> defines android_focused.png as the image when the button is focused (when the button is highlighted using the trackball or directional pad); and the third <item> definesandroid_normal.png as the image for the normal state (when neither pressed nor focused). This XML file now represents a single drawable resource and when referenced by a Button for its background, the image displayed will change based on these three states.
Note: The order of the <item> elements is important. When this drawable is referenced, the <item>s are traversed in-order to determine which one is appropriate for the current button state. Because the "normal" image is last, it is only applied when the conditionsandroid:state_pressed and android:state_focused have both evaluated false.
Open the res/layout/main.xml file and add the Button element:
The android:background attribute specifies the drawable resource to use for the button background (which, when saved atres/drawable/android.xml, is referenced as @drawable/android). This replaces the normal background image used for buttons throughout the system. In order for the drawable to change its image based on the button state, the image must be applied to the background.
To make the button do something when pressed, add the following code at the end of the onCreate() method: