一.“初次邂逅”
在我們構建設定介面的時候會用到ListPreference這個控制項,預設(2.3之前)是單選,但我們現在想要多選,就像所示
二.“先看外表”
我們的項目結構如下:
首先我們先看布局檔案
preference_layout.xml
<?xml version="1.0" encoding="utf-8"?><PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"><com.u0fly.MutiSelectListPreference.MutiSelectListPreferenceandroid:defaultValue="a" android:key="muti_select_list_preference" android:title="@string/title_muti_select_list_preference"android:dialogTitle="@string/dialog_title_muti_select_list_preference" android:summary="@string/summary_muti_select_list_preference"android:entries="@array/entries_muti_select_list_preference" android:entryValues="@array/entries_values_muti_select_list_preference"></com.u0fly.MutiSelectListPreference.MutiSelectListPreference></PreferenceScreen>
這樣我們就構建出上面一開始我們看到的那個多選的對話方塊了
我們用<com.u0fly.MutiSelectListPreference.MutiSelectListPreference>代替了我們之前系統提供的ListPreference
當然我們還要自己構建一個相應的類,該類繼承自ListPreference
裡面要重寫下面這兩個方法:
onPrepareDialogBuilder和onDialogClosed
下面是string.xml和arrays.xml中的內容,大家可以根據自己的需要進行修改:
<?xml version="1.0" encoding="utf-8"?><resources> <string name="hello">Hello World, MutiSelectListPreference!</string> <string name="app_name">MutiSelectListPreference</string> <string name="title_muti_select_list_preference">多選設定</string> <string name="dialog_title_muti_select_list_preference">請選擇多個選項</string> <string name="summary_muti_select_list_preference">支援多選的設定</string></resources>
<?xml version="1.0" encoding="utf-8"?><resources><string-array name="entries_muti_select_list_preference"><item>item a</item><item>item b</item><item>item c</item><item>item d</item><item>item e</item><item>item f</item></string-array><string-array name="entries_values_muti_select_list_preference"><item>a</item><item>b</item><item>c</item><item>d</item><item>e</item><item>f</item></string-array></resources>
三.“深入瞭解”
接下來我們來看看構建出這個多選設定的類 MutiSelectListPreference
package com.u0fly.MutiSelectListPreference;import android.app.AlertDialog.Builder;import android.content.Context;import android.content.DialogInterface;import android.preference.ListPreference;import android.util.AttributeSet;import android.util.Log;public class MutiSelectListPreference extends ListPreference {private static final String TAG = "u0fly -------->";private static final String SEPARATOR = "u0fly_@#asdf*&_ylf0u";private boolean[] mClickedDialogEntryIndices; public MutiSelectListPreference(Context context, AttributeSet attrs) {super(context, attrs);// TODO Auto-generated constructor stubmClickedDialogEntryIndices = new boolean[getEntries().length];} @Overridepublic void setEntries(CharSequence[] entries) {super.setEntries(entries);mClickedDialogEntryIndices = new boolean[entries.length];}public MutiSelectListPreference(Context context) {this(context, null);}@Overrideprotected void onDialogClosed(boolean positiveResult) {// TODO Auto-generated method stubCharSequence[] entryValues = getEntryValues();if (positiveResult && entryValues != null) {StringBuffer value = new StringBuffer();for (int i = 0; i < entryValues.length; i++) {if (mClickedDialogEntryIndices[i]) {value.append(entryValues[i]).append(SEPARATOR);}}if (callChangeListener(value)) {String val = value.toString();if (val.length() > 0)val = val.substring(0, val.length() - SEPARATOR.length());setValue(val);}}}@Overrideprotected void onPrepareDialogBuilder(Builder builder) {// TODO Auto-generated method stubCharSequence[] entries = getEntries();CharSequence[] entryValues = getEntryValues();Log.d(TAG , "onPrepareDialogBuilder entries = "+ entries.toString() + " entryValues = " + entryValues.toString());if (entries == null || entryValues == null|| entries.length != entryValues.length) {throw new IllegalStateException("ListPreference requires an entries array and an entryValues array which are both the same length");}restoreCheckedEntries();builder.setMultiChoiceItems(entries, mClickedDialogEntryIndices,new DialogInterface.OnMultiChoiceClickListener() {public void onClick(DialogInterface dialog, int which,boolean val) {Log.d("u0fly------>", "OnMultiChoiceClickListener val = "+ val);mClickedDialogEntryIndices[which] = val;}});}public static String[] parseStoredValue(CharSequence val) {Log.d("u0fly----->", "parseStoredValue val = " + val.toString());if ("".equals(val))return null;elsereturn ((String) val).split(SEPARATOR);}private void restoreCheckedEntries() {CharSequence[] entryValues = getEntryValues();String[] vals = parseStoredValue(getValue());if (vals != null) {Log.d("u0fly----->", "restoreCheckedEntries vals = " + vals);for (int j = 0; j < vals.length; j++) {Log.d("u0fly----->", "restoreCheckedEntries val without trim = " + vals[j]);String val = vals[j].trim();Log.d("u0fly----->", "restoreCheckedEntries val = " + val);for (int i = 0; i < entryValues.length; i++) {CharSequence entry = entryValues[i];if (entry.equals(val)) {mClickedDialogEntryIndices[i] = true;break;}}}}}}
前面的布局檔案就是通過這個類來構建出多選設定介面的
通過com.u0fly.MutiSelectListPreference.MutiSelectListPreference
main.java 通過xml的形式載入設定介面,前面的文章我們也用過,通過監聽onPreferenceChange可以添加具體操作
具體參考:http://blog.csdn.net/u0fly/archive/2011/04/28/6370008.aspx
/**@author u0fly,2011-5-11**Blog: [url]http://www.cnblogs.com/u0fly/[/url]**/package com.u0fly.MutiSelectListPreference;import android.os.Bundle;import android.preference.PreferenceActivity;public class Main extends PreferenceActivity{/** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resourceaddPreferencesFromResource(R.xml.preference_layout); }}
參考:
http://blog.350nice.com/wp/archives/240
小技巧:
一句話添加管理應用程式的設定選項
<PreferenceScreen android:title="Manage Package Storage" android:summary="Uninstall APK"> <intent android:action="android.intent.action.MANAGE_PACKAGE_STORAGE"/></PreferenceScreen>