Android中设置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啦。

猜你喜欢

转载自blog.csdn.net/tiankongcheng6/article/details/79352539