To fix this, first 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 23.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 make use of 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 your drawable folder.
Listing 23.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 23.6 Applying a state list drawable (res/values/styles.xml
)
<resources> <style name="AppTheme" parent="Theme.AppCompat"> ... </style> <style name="BeatBoxButton" parent="android:style/Widget.Holo.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 23.4). Pretty slick, right?
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/guide/topics/resources/drawable-resource.html#StateList for details.