在使用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; } }