在Android應(yīng)用中,絕大部分情況下,按鈕都有按下變色的效果,這種效果主要都是借助于Android里面的 StateListDrawable來實(shí)現(xiàn)的,它可以設(shè)置多種狀態(tài),并分別為每種狀態(tài)設(shè)置相應(yīng)的drawable,這個drawable有兩種方式來實(shí)現(xiàn):1、準(zhǔn)備多張圖片 2、準(zhǔn)備多個 ShapeDrawable。下面用第二種方式來實(shí)現(xiàn)一下按鈕變色的效果。
一、準(zhǔn)備兩個ShapeDrawable
1、btn_shape.xml,正常狀態(tài)下的背景圖
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp" />
<solid android:color="@color/material_green" />
</shape>
2、btn_shape_press.xml ,按下狀態(tài)下的背景圖
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="5dp" />
<solid android:color="@color/material_dark_green" />
</shape>
其中,corners:圓角度數(shù), solid:填充色
二、準(zhǔn)備StateListDrawable
btn_shape_press.xml
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 觸摸模式下單擊時的背景圖片-->
<item android:drawable="@drawable/btn_shape_press" android:state_pressed="true" />
<!-- 默認(rèn)時的背景圖片-->
<item android:drawable="@drawable/btn_shape" />
</selector>
三、將StateListDrawable設(shè)置為Button的背景
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:background="@drawable/btn_selector"
android:text="請按我,給你點(diǎn)顏色看看"
android:textColor="@color/white"></Button>
</RelativeLayout>
測試效果

按鈕點(diǎn)擊變色.gif