昨天與人討論checkbox的樣式問題,常見的自定義樣式是改變checkbox的button圖片,但是他的需求是去掉checkbox的選項框,使checkbox的樣式類似button。我最初給的建議是使用TextView,點擊一次改變背景顏色,然后保存當前狀態(選中或未選中),但還是很麻煩,查找資料,找到了第二種checkbox的自定義樣式方式,總結一下,備忘。
一、修改checkbox選項框樣式
首先我們要找到兩張checkbox選項框的圖片:
normal.png
checked.png
然后我們設置一個背景選擇器checkbox_style.xml:
<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/checked" android:state_checked="true"/> <item android:drawable="@drawable/normal" android:state_checked="false"/> <item android:drawable="@drawable/normal"/> </selector>
到這里,在往下有兩種方案,一種是直接在布局文件的android:button屬性中設置:
1 2 <CheckBox 3 android:id="@+id/checkbox1" 4 android:layout_width="wrap_content" 5 android:layout_height="wrap_content" 6 android:text="@strings/check_text" 7 android:button="@drawable/checkbox_style" 8 android:checked="true"/>
還有一種是在style.xml文件中添加樣式MyCheckboxStyle,並在布局文件中的style屬性中設置:
1 <style name="MyCheckboxStyle" parent="@android:style/Widget.CompoundButton.CheckBox"> 2 <item name="android:button">@drawable/checkbox_style</item> 3 </style>
1 <CheckBox 2 android:id="@+id/checkbox1" 3 android:layout_width="wrap_content" 4 android:layout_height="wrap_content" 5 style="@style/MyCheckboxStyle" />
二、去掉選項框,自定義類Button樣式
同樣,我們需要來一個selector checkbox_style.xml,但是這里的圖片就不是選項框的圖片了,而是整個checkbox的背景圖片
1 <?xml version="1.0" encoding="utf-8"?> 2 <selector xmlns:android="http://schemas.android.com/apk/res/android"> 3 4 <item android:drawable="@drawable/checked" android:state_checked="true"/> 5 <item android:drawable="@drawable/normal" android:state_checked="false"/> 6 <item android:drawable="@drawable/normal"/>
然后,我們可以在布局文件中將android:button屬性設置為“@null”來去掉選項框,並且在android:background屬性中設置:
1 2 <CheckBox 3 android:id="@+id/checkbox1" 4 android:layout_width="wrap_content" 5 android:layout_height="wrap_content" 6 android:background="@drawable/checkbox_style" 7 android:button="@null" 8 android:checked="true"/>
OK,這就是兩種自定義樣式的CheckBox啦。