天天看點

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

在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>
           

測試效果

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

按鈕點選變色.gif

繼續閱讀