1.首先在drawable文件夹中添加drawable文件checkbox_style.xml。
- <?xml version="1.0" encoding="utf-8"?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
-
- <item android:drawable="@drawable/checkbox_pressed" android:state_checked="true"/>
- <item android:drawable="@drawable/checkbox_normal" android:state_checked="false"/>
- <item android:drawable="@drawable/checkbox_normal"/>
-
- </selector>
2.在values文件夹下的styles.xml文件中添加CustomCheckboxTheme样式。
- <style name="CustomCheckboxTheme" parent="@android:style/Widget.CompoundButton.CheckBox">
- <item name="android:button">@drawable/checkbox_style</item>
- </style>
3.在布局文件中使用CustomCheckboxTheme样式。
- <CheckBox
- android:id="@+id/select_all"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- style="@style/CustomCheckboxTheme" />
使用到的图片资源
checkbox_normal.png
checkbox_pressed.png
在使用Android的Preference,有时为了让我们的界面更加美观,我们会自定义自己的Preference。今天就主要说一下怎样自定义CheckBoxPreference的CheckBox按钮。
系统默认CheckBoxPreference的CheckBox样式

自定义后的CheckBox样式

其实,关键的一步就是指定CheckBoxPreference的android:widgetLayout属性,详细步骤就不说了,下面直接上代码,很简单的。
1./res/xml/my_preference.xml
- <?xml version="1.0" encoding="utf-8"?>
- <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
-
- <CheckBoxPreference
- android:key="cbp"
- android:summaryOff="Off"
- android:summaryOn="On"
- android:title="CheckBoxPreference"
- android:widgetLayout="@layout/my_checkbox" />
-
- </PreferenceScreen>
2./res/layout/my_checkbox.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:button="@drawable/checkbox_checked_style"
- android:clickable="false"
- android:focusable="false" />
3./res/drawable/checkbox_checked_style.xml
- <?xml version="1.0" encoding="utf-8"?>
- <selector xmlns:android="http://schemas.android.com/apk/res/android">
-
- <item android:drawable="@drawable/icon_checkbox_unchecked" android:state_checked="false"/>
- <item android:drawable="@drawable/icon_checkbox_checked" android:state_checked="true"/>
-
- </selector>
4.MainActivity.java注意要继承PreferenceActivity
- public class MainActivity extends PreferenceActivity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- addPreferencesFromResource(R.xml.my_preference);
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
-
- }
[转]Android中自定义checkbox样式
原文:http://www.cnblogs.com/ZhuRenWang/p/4856143.html