Android開發之給你的Button加個背景

YungFan發表於2017-12-13

在Android應用中,絕大部分情況下,按鈕都有按下變色的效果,這種效果主要都是藉助於Android裡面的 StateListDrawable來實現的,它可以設定多種狀態,並分別為每種狀態設定相應的drawable,這個drawable有兩種方式來實現:1、準備多張圖片 2、準備多個 ShapeDrawable。下面用第二種方式來實現一下按鈕變色的效果。

一、準備兩個ShapeDrawable

1、btn_shape.xml,正常狀態下的背景圖

<?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 ,按下狀態下的背景圖

<?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:圓角度數, solid:填充色

二、準備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" />
    <!-- 預設時的背景圖片-->
    <item android:drawable="@drawable/btn_shape" />
</selector>  
複製程式碼

三、將StateListDrawable設定為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="請按我,給你點顏色看看"
        android:textColor="@color/white"></Button>
</RelativeLayout>
複製程式碼

測試效果

按鈕點選變色.gif

相關文章