Chapter 23 XML Drawables
For the More Curious: 9-Patch Images
Sometimes (or maybe often), you will fall back to regular old image files for your button backgrounds.
But what happens to those image files when your button can be displayed at many different sizes?
If the width of the button is greater than the width of its background image, the image just stretches,
right? Is that always going to look good?
Uniformly stretching your background image will not always look right. Sometimes you need more
control over how the image will stretch.
In this section, you will convert BeatBox to use a 9-patch image as the background for the buttons
(more on what that means in just a moment). This is not because it is necessarily a better solution for
BeatBox – it is a way for you to see how a 9-patch works for those times when you want to use an
image file.
First, modify list_item_sound.xml to allow the button size to change based on the available space.
Listing 23.8 Letting those buttons stretch
(res/layout/list_item_sound.xml)
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
type="com.bignerdranch.android.beatbox.SoundViewModel"/>
android:layout_height="wrap_content"
android:layout_margin="8dp">
android:layout_width="100dp match_parent"
android:layout_height="100dp match_parent"
android:layout_gravity="center"
android:onClick="@{() -> viewModel.onButtonClicked()}"
android:text="@{viewModel.title}"
tools:text="Sound name"/>
Now the buttons will take up the available space, leaving an 8dp margin. The image in Figure 23.7,
with a snazzy folded corner and shadow, will be your new button background.
Figure 23.7 A new button background image
(res/drawable-xxhdpi/ic_button_beat_box_default.png)