選擇器可以減少不少的邏輯代碼 精簡代碼量。如下圖 首頁的RadioButton有選中和非選中兩種狀態 文字有灰色和藍色兩種狀態 圖片也有兩種狀態。
RadioButton 佈局:
<RadioButton
android:id="@+id/auction_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:drawableTop="@drawable/auction_home" //auction_home爲圖片選擇器
android:button="@null"
android:gravity="center"
android:checked="true"
android:text="首頁"
android:textSize="12sp"
android:layout_marginTop="2dp"
android:textColor="@drawable/auction_text" //auction文字顏色的選擇器
/>
在drawable資源文件下新建 圖片選擇器 auction_home.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/auction_sort_hide" android:state_checked="false" ></item>
<item android:drawable="@drawable/auction_sort_show" android:state_checked="true" ></item>
//如果爲checked狀態 RadioButton背景圖片設置爲auction_sort_show資源圖片 否爲auctio_sort_hide
</selector>
在drawable資源文件下新建文字選擇器 auction_text.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:color="@color/hui" android:state_checked="false" ></item>
<item android:color="@color/he" android:state_checked="true" ></item>
</selector>