在使用Android的Preference,有时为了让咱们的界面更加美观,咱们会自定义本身的Preference。今天就主要说一下怎样自定义CheckBoxPreference的CheckBox按钮。java
系统默认CheckBoxPreference的CheckBox样式android
自定义后的CheckBox样式web
其实,关键的一步就是指定CheckBoxPreference的android:widgetLayout属性,详细步骤就不说了,下面直接上代码,很简单的。ide
1./res/xml/my_preference.xmlspa
<?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.xmlcode
<?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.xmlorm
<?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注意要继承PreferenceActivityxml
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; } }