自定义checkbox首选项

我无法自定义我的checkbox,虽然我已经在XML偏好文件中定义了背景,但它并不拉取文件。 1.我试图显示checkbox的自定义图像,并已将select器xml定义为“android_button.xml”,如下所示:

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checkable="true" android:drawable="@drawable/state_normal" /> <!-- pressed --> <item android:state_checked="true" android:drawable="@drawable/android_pressed" /> <!-- focused --> <item android:drawable="@drawable/state_normal" /> <!-- default --> </selector> 

state_normal和android_pressed是res> drawable文件夹中的两个.png图像。

2.my Checkbox的preference.xml文件是:

  <CheckBoxPreference android:key="@string/Drop_Option" android:title="Close after call drop" android:defaultValue="true" android:background="@drawable/android_button" /> 

定义中是否有任何错误,屏幕上显示的唯一更改是android:标题文本,如果更改文本,则会更改文本。 没有别的改变。 我该如何解决。 谢谢你的build议。

有两种方法可以实现你所需要的,首先是在res / layout中定义自定义checkbox布局custom_chexbox.xml:

 <?xml version="1.0" encoding="UTF-8"?> <CheckBox xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+android:id/checkbox" android:layout_width="wrap_content" android:layout_height="wrap_content" android:focusable="false" android:clickable="false" android:button="@drawable/android_button"/> 

然后,您需要为首选项指定此布局:

 <CheckBoxPreference android:key="@string/Drop_Option" android:title="Close after call drop" android:defaultValue="true" android:widgetLayout="@layout/custom_checkbox"/> 

第二种方法是创build自定义主题,为checkbox视图重新定义样式并将主题应用于首选项活动,请参阅如何在对话框中自定义android中CheckMark颜色的颜色。 :android的细节。

制作一个drwable xml文件:

 <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/checkbox_active_btn" android:state_checked="true"></item> <item android:drawable="@drawable/checkbox_active_btn" android:state_checked="true" android:state_enabled="false" android:state_focused="true"></item> <item android:drawable="@drawable/checkbox_active_btn" android:state_checked="true" android:state_enabled="false"></item> <item android:drawable="@drawable/checkbox_active_btn" android:state_checked="true" android:state_focused="true"></item> <item android:drawable="@drawable/checkbox_active_btn" android:state_checked="true" android:state_pressed="true"></item> <item android:drawable="@drawable/checkbox_inactive_btn" android:state_checked="false"></item> <item android:drawable="@drawable/checkbox_inactive_btn" android:state_checked="false" android:state_enabled="false" android:state_focused="true"></item> <item android:drawable="@drawable/checkbox_inactive_btn" android:state_checked="false" android:state_enabled="false"></item> <item android:drawable="@drawable/checkbox_inactive_btn" android:state_checked="false" android:state_focused="true"></item> <item android:drawable="@drawable/checkbox_inactive_btn" android:state_checked="false" android:state_pressed="true"></item> </selector> 

通过cb.setButtonDrawable(R.drawable.checkboxcustom)以编程方式设置它;