天天看點

Android自定義按鈕樣式

使得按鈕在不同的狀态有不同的背景圖檔是本篇的主要類容

在res/drawable下建立一個buttonstyle.xml檔案,這個檔案用于描述按鈕的樣式

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_pressed="true" android:drawable="@drawable/btn_p"/>
    <item android:state_pressed="false" android:drawable="@drawable/btn_n"/>
</selector>
           

還有很多的樣式如下圖

Android自定義按鈕樣式

在布局檔案中添加一個Button,使用buttonstyle.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/buttonstyle"
        />

</LinearLayout>
           

這樣就完成了Button的樣式。

繼續閱讀