Android開發(fā)之給你的Button加個背景

在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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容