统一按钮样式
1.定义XML drawable之前,先修改list item sound.xml文件隔开按钮,代码如下
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
23.2 shape drawable 369
<data>
<variable
name="viewModel"
type="com.bignerdranch.android.beatbox.SoundVieModel"/>
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout height="wrap__content"
android:layout_margin="8dp">
<Button
android:layout_width="match_parent"
android:layout_height="120dp"
android:layout width="100dp"
android:layout_height="100dp"
android:layout_gravity="center" 23
android:onClick="@[()-> viewModel.onButtonClicked())"
android:text="@(viewModel.title)"
tools:text="Sound name"/>
</FrameLayout>
s/lavout>
shape drawable
2.打开项目工具窗口,在res/drawable目录下创建一个名为button_beat_box_normal.xml的文件,如代码所示。(稍后还会创建一个“非正常”的文件,所以文件名里有normal字样。)
(res/drawable/button_beat_box_normal.xml)
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:color="@color/dark_blue"/>
</shape>
3.在styles.xml中,使用新建的button_beat_box_normal作为按钮背景,如代码所示
<resources>
<style name="AppTheme" parent="Theme.AppCompat">
</style>
<style name="BeatBoxButton"parent="Widget.AppCompat.Button">
<item name="android:background">@color/dark blue</item>
<item name="android:background">@drawable/button_beat_box_normal</item> </style>
</resources>
state list drawable
4.定义按钮按下时的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>
5.创建一个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>
6.使用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>
layer list drawable
7.使用layer list drawable (res/drawable/button_beat_box_pressed.xml)
<layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <item>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid
android:color="@color/red"/>
</shape>
</item>
sitem>
<shape
23.5 深入学习:为什么要用XML drawable 373
android:shape="oval">
<stroke
android:width="4dp"
android:color="@color/dark_red"/>
</shape>
</item>
</layer-list>
8.现在,BeatBox应用真正完成了,运行结果如下图