Step by step with me ---- Android preferenceactivity setting interface-multiple options-listpreference

Source: Internet
Author: User

 

1. "First Encounter"
The listpreference control is used when we build the setting interface. By default (before 2.3), it is a single choice, but we want to select multiple options, as shown in

2. "first look at the appearance"
Our project structure is as follows:
 
First, let's look at the layout file.
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>
In this way, we will build the multi-choice dialog box we saw at the beginning.
We used <com. u0fly. mutiselectlistpreference. mutiselectlistpreference> to replace the listpreference provided by our system.
Of course, we also need to build a corresponding class that inherits from listpreference.
The following two methods must be rewritten:
Onpreparedialogbuilder and ondialogclosed
The following are the content in string. xml and arrays. xml. You can modify it as needed:
<? 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"> multiple choice Settings </string> <string name = "marker"> Please select multiple options </string> <string name = "summary_muti_select_list_preference"> multiple options </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>
3. "in-depth understanding"
Next, let's take a look at the mutiselectlistpreference class that builds this multi-choice setting.
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;}}}}}}
The preceding layout file uses this class to build the multi-choice setting interface.
PassCom. u0fly. mutiselectlistpreference. mutiselectlistpreference
Main. Java loads the settings interface in XML format. We have also used the previous article. You can add specific operations by listening to onpreferencechange.
Reference: 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);    }}
Refer:
http://blog.350nice.com/wp/archives/240

TIPS:
Setting options for managing applications in one sentence
<PreferenceScreen android:title="Manage Package Storage" android:summary="Uninstall APK">        <intent android:action="android.intent.action.MANAGE_PACKAGE_STORAGE"/></PreferenceScreen>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.