昨天与人讨论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 <CheckBox3 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 <CheckBox2 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 <CheckBox3 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啦。