Basic Applications of the Preference System Detailed by Android-Preference (3)

Keywords: Android xml encoding

This article will systematically provide the application and management of CheckBox Preference, EditText Edit Preference, List Preference, MultiSelect List Preference, Switch Preference.

I. Preference Tree Structure

First, we will review the tree structure of the Preference system to deepen the inheritance relationship between them.

Dialog Preference System

Dialog Preference is an abstract class that inherits directly from Preference. Its unique feature is that it is based on Dialog. That is to say, when we click on the corresponding Dialog Preference system, it is presented in the form of Dialog. The system provides us with the following subclasses: EditTextPreference, ListPreference and MultSelectListPreference.

1. Common Characters of Dialog Preference System

We all know that Dialog Preference is based on Dialog. When we click on it, it will be displayed as a dialog box. So besides inheriting the properties from Preference, we also add many unique properties and methods.

1.1. Dialog Preference System Unique Attributes

1.2. Dialog Preference's unique approach

There are only three useful callback methods listed here. Other setter, gettter and other methods are not listed due to space issues (the same below).

2. Application and Management of Dialog Preference System

1,EditTextPreference

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
android:key="using_categories_in_root_screen"
android:summary="Using Preference Categories"
android:title="Categories">
<EditTextPreference
    android:key="key_prerence"
    android:title="Preferece Title"
    android:summary="Preference Summary"
    />
</PreferenceScreen>

2,ListPreference

ListPreference, like other Preferences, also uses Shared Preferences to store and update, especially because Shared Preferences stores the value of Android: entryValues (that is, android: entryValues corresponds to keys one by one to form key-value pairs), while Android: entries displays the interface with android:entries: EntryValues correspond to each other.

2.1. Specific attributes of ListPreference

2.2. List Preference's Special Method

2.3. List Preference Application

List data source character array:

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="game">
    <item>Dota</item>
    <item>Dota2</item>
    <item>NBA2K10</item>
    <item>FIFA2K10</item>
</string-array>
<string-array name="game_index">
    <item>0</item>
    <item>1</item>
    <item>2</item>
    <item>3</item>
</string-array>
</resources>

ListPreference's xml file:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
    android:icon="@mipmap/ic_launcher"
    android:title="ListPreference"
    android:summary="ListPreference summary"
    android:dialogIcon="@mipmap/ic_blue_launcher"
    android:dialogTitle="Favourite Games"
    android:key="key_listpreference"
    android:entries="@array/game"
    android:entryValues="@array/game_index"
    />
</PreferenceScreen>

Implementation of PreferenceActivity:

public class ListPreferenceActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener{
private ListPreference preference;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.list_preference);
    init();
}
private void init(){
    preference= (ListPreference) findPreference("key_listpreference");
    /// preference. setOnPreference ClickListener (this); ****** Click Event has been overwritten ****
    preference.setOnPreferenceChangeListener(this);
    // Set summary to the list value of the selected values
    if(preference.getEntry()!=null) {
        preference.setSummary(preference.getEntry());//Set summary at initialization
    }
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    /*newValue The value returned is the value of getEntries
    * 01-09 12:30:43.558 15872-15872/com.crazymo.prerencescreen D/TAG2: onPreferenceChange run1
    * 01-09 12:41:10.627 15872-15872/com.crazymo.prerencescreen D/TAG2: onPreferenceChange run2
    * */
    if(preference instanceof ListPreference) {
        ListPreference listPreference = (ListPreference) preference;//Force preference, a Preference, to a ListPreference type
        CharSequence[] entries = listPreference.getEntries();//Get the entity content in ListPreference
        int index = listPreference.findIndexOfValue((String) newValue);//Get the subscript value of the entity content in ListPreference
        listPreference.setSummary(entries[index]);//The sumamry in listPreference is displayed as selected from the current ListPreference entity content
        Log.d("TAG2", "onPreferenceChange run"+newValue);
        Toast.makeText(ListPreferenceActivity.this,entries[index].toString(),Toast.LENGTH_LONG).show();
    }
    return true;
}

}

3,MultiSelectListPreference

MultiSelect List Preference and List Preference are both list-based Dialog Preferences. The difference is that List Preference provides a list of radio selections. After Android 3.0, multiple selections can be achieved through MultiSelect List Preference, so their attributes and methods are almost the same, including the use of basic grammar, but It's important to note that Shared Preferences of MultiSelectList Preferences saves the set of collections (we should have this concept set for storing multiple objects), so it's a bit cumbersome to process when reading data.

3.1. New Method of MultiSelectList Preference

3.2. MultiSelectList Preference Application

Or use the same data source, the same xml (change List Preference to MultiSelect List Preference, other unchanged)

public class MutilListPreferenceActivity extends PreferenceActivity implements OnPreferenceChangeListener {
private MultiSelectListPreference preference;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.list_preference);
    preference= (MultiSelectListPreference) findPreference("key_listpreference");
    preference.setOnPreferenceChangeListener(this);
    initFromSharedPreferences();
}
private void initFromSharedPreferences(){
    String summary=null;
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    Set<String>options = prefs.getStringSet("key_listpreference", null);  //Because the initial value is not set, null will be judged.
    if(options!=null) {
        CharSequence[] extras = preference.getEntries();
        for (String op : options) {
            int index = preference.findIndexOfValue(op);
            if (summary==null) {
               summary="";
            }
            summary = summary + extras[index];            }
        preference.setSummary(summary);
    }
}

@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
    if(preference instanceof MultiSelectListPreference) {
        String summary=null;
        MultiSelectListPreference multiSelectListPreference=(MultiSelectListPreference)preference;
        CharSequence[] extras =  multiSelectListPreference.getEntries();

        Set<String> options=(Set<String>)newValue;
        for (String op : options){
            int index = multiSelectListPreference.findIndexOfValue(op);
            Log.d("TAG2", op + extras[index]);
            if(summary==null) {
                summary="";
            }
            summary = summary + extras[index];
        }
        Log.d("TAG2","onPreferenceChange:::"+summary);
        multiSelectListPreference.setSummary(summary);
    }
    return true;
}

}

3. TwoState Preference System

TwoStatePreference is also an abstract class that functions literally. Based on two optional states of the preferred base class, he does not add unique attributes, all inherit superiors, in Shared Preferences by maintaining a Boolean value (checked when true) to set the current state of the enabled and prohibited Preference. Android also provides us with two options: CheckBox Preference and Switch Preference for our direct use.

1. The commonness of TwoState Preference

** 2. Application and Management of TwoState Preference
1,CheckBoxPreference
1.1. New attributes of CheckBox Preference**

1.2. CheckBox Preference Application

res/xml/widget_layout.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:layout_gravity="center"
    android:button="@mipmap/ic_bt_config"
    android:clickable="false"
    android:focusable="false" />

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
    android:icon="@mipmap/ic_launcher"
    android:key="key_checkboxprefs"
    android:title="CheckBoxPreference"
    android:summary="CheckBoxPreference summary"
    android:summaryOff="Summary off"
    android:summaryOn="On Summary"
    android:order="10"
    />
<CheckBoxPreference
    android:icon="@mipmap/ic_blue_launcher"
    android:key="key_checkboxprefs2"
    android:title="CheckBoxPreference2"
    android:summary="CheckBoxPreference2 summary"
    android:summaryOff=" Off Summary2"
    android:summaryOn="On Summary2"
    android:order="1"
    android:widgetLayout="@xml/widget_layout"
    />
</PreferenceScreen>

Each click executes onChange before onClick:

01-10 11:16:56.459 31292-31292/com.crazymo.prerencescreen D/TAG2: true
01-10 11:16:56.464 31292-31292/com.crazymo.prerencescreen D/TAG2: CheckBox Clicked!!
01-10 11:36:19.660 31292-31292/com.crazymo.prerencescreen D/TAG2: false
01-10 11:36:19.662 31292-31292/com.crazymo.prerencescreen D/TAG2: CheckBox Clicked!

2,SwitchPreference

2.1. SwitchPreference Added Attributes

2.2. Switch Preference Application

Each click executes onChange before onClick:

01-10 11:47:55.554 12915-12915/com.crazymo.prerencescreen D/TAG2: true
01-10 11:47:55.559 12915-12915/com.crazymo.prerencescreen D/TAG2: SwitchPrefeence

In these three articles, we have finally clarified the application of Preference and some simple principles. In fact, we do not need to recite grammar or api. We need to understand them from the principles, from their structural relations, and to investigate their fundamentals. Preference just saves data as the key in Shared Preferences, and then reads and refreshes the UI automatically by Activity when it enters the interface again. Different Preferences save Shared Preferences in different formats, such as TwoState Preference saves boolean key pairs, List Preference saves boolean key pairs. Save common string key-value pairs; MultiSelectList Preference saves set sets and so on to save multiple sets of data. The principle can be summed up in two steps: Shared Preferences data saving and Reference Activity reading Shared Prefences data and updating.

If you have any questions, please pay attention to my public number, and we will continue to communicate!

Posted by Iasonic on Mon, 08 Jul 2019 15:42:41 -0700