In this article

Custom Button

02/06/2018

2 minutes to read

Contributors

In this article

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.

Right-click and download the three images below, then copy them to
the Resources/drawable directory of your project. These will be
used for the different button states.

Create a new file in the Resources/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>
defines android_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> defines android_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 conditions android:state_pressed and
android:state_focused have both evaluated false.

The android:background attribute specifies the drawable resource
to use for the button background (which, when saved at
Resources/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: