State List Drawables

To fix this, define a new shape drawable that will be used for the pressed state of the button.

Create button_beat_box_pressed.xml in res/drawable. Make this pressed drawable the same as the normal version but with a red background color.

Listing 22.4  Defining a pressed shape drawable (res/drawable/button_beat_box_pressed.xml)

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="oval">

    <solid android:color="@color/red"/>

</shape>

Next, you are going to use this pressed version when the user presses the button. To do this, you will use a state list drawable.

A state list drawable is a drawable that points to other drawables based on the state of something. A button has a pressed and an unpressed state. You will use a state list drawable to specify one drawable as the background when pressed and a different drawable when not pressed.

Define a state list drawable in a new file in your res/drawable folder.

Listing 22.5  Creating a state list drawable (res/drawable/button_beat_box.xml)

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_beat_box_pressed"
          android:state_pressed="true"/>
    <item android:drawable="@drawable/button_beat_box_normal" />
</selector>

Now, modify your button style to use this new state list drawable as the button background.

Listing 22.6  Applying a state list drawable (res/values/styles.xml)

<resources>

    <style name="AppTheme" parent="Theme.AppCompat">
        ...
    </style>

    <style name="BeatBoxButton" parent="Widget.AppCompat.Button">
        <item name="android:background">@drawable/button_beat_box_normal</item>
        <item name="android:background">@drawable/button_beat_box</item>
    </style>

</resources>

When the button is in the pressed state, button_beat_box_pressed will be used as the background. Otherwise, button_beat_box_normal will be the background of the button.

Run BeatBox and press a button. The button’s background changes (Figure 22.4). Pretty slick, right?

Figure 22.4  BeatBox, now with a pressed button state

BeatBox, now with a pressed button state

State list drawables are a handy customization tool. Many other states are also supported, including disabled, focused, and activated. Check out the documentation at developer.android.com/​reference/​android/​graphics/​drawable/​StateListDrawable for details.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.42.168