常見(jiàn)的自定義樣式是改變checkbox的button圖片嗤瞎,但是他的需求是去掉checkbox的選項(xiàng)框,使checkbox的樣式類(lèi)似button。我最初給的建議是使用TextView,點(diǎn)擊一次改變背景顏色澜公,然后保存當(dāng)前狀態(tài)(選中或未選中),但還是很麻煩喇肋,查找資料坟乾,找到了第二種checkbox的自定義樣式方式,總結(jié)一下蝶防,備忘甚侣。
一、修改checkbox選項(xiàng)框樣式
首先我們要找到兩張checkbox選項(xiàng)框的圖片:
normal.png
checked.png
然后我們?cè)O(shè)置一個(gè)背景選擇器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屬性中設(shè)置:
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屬性中設(shè)置:
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" />
二、去掉選項(xiàng)框宗兼,自定義類(lèi)Button樣式
同樣躏鱼,我們需要來(lái)一個(gè)selector checkbox_style.xml,但是這里的圖片就不是選項(xiàng)框的圖片了殷绍,而是整個(gè)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屬性設(shè)置為“@null”來(lái)去掉選項(xiàng)框,并且在android:background屬性中設(shè)置:
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啦主到。
————————————————
版權(quán)聲明:本文為CSDN博主「myf0908」的原創(chuàng)文章茶行,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明登钥。
原文鏈接:https://blog.csdn.net/myf0908/article/details/76502009