This is how we use SharedPreferences most of the time

SharedPreferences sharedPreferences = getSharedPreferences("eric", Context.MODE_PRIVATE); // Private data Editor Editor = sharedPreferences. Edit (); Editor.putstring ("name"."eric");
editor.putInt("age", 4); editor.commit(); // Commit the changesCopy the code

In the app Settings page development will also use to save the Settings, we will also use SharedPreferences to save these Settings, Android official provides a simpler for the Settings page using SharedPreferences method, That’s PreferenceActivity and PreferenceFragment. Here’s how to use it. PreferenceActivity is mainly aimed at versions prior to 3.0, and PreferenceFragment is more flexible. In fact, the method of using PreferenceActivity is roughly the same as that of using PreferenceFragment. Using a PreferenceFragment normally requires a layout to be associated with a layout. In a PreferenceFragment, you don’t need to do that. You need to customize XML and add a preference. The.xml root node must be a PreferenceScreen element. The children of the PreferenceScreen are displayed as a separate control and have a save property.

<? xml version="1.0" encoding="utf-8"? > <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <CheckBoxPreference
        android:key="checkbox_preference"
        android:title="@string/title_checkbox_preference"
        android:summary="@string/summary_checkbox_preference" />
    <ListPreference
        android:key="list_preference"
        android:title="@string/title_list_preference"
        android:summary="@string/summary_list_preference"
        android:entries="@array/entries_list_preference"
        android:entryValues="@array/entryvalues_list_preference"
        android:dialogTitle="@string/dialog_title_list_preference" />
</PreferenceScreen>
Copy the code

It should look like this

CheckBoxPreference and ListPreference are only shown above, and there are many other Preference controls. For details, you can check the official documentation about the word class of Preference. If there are too many items, we can classify them and display them in the following two ways.

Use the title

Add the PreferenceCategory attribute to separate headings.

<? xml version="1.0" encoding="utf-8"? > <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title="@string/inline_preferences">

        <CheckBoxPreference
            android:key="checkbox_preference"
            android:summary="@string/summary_checkbox_preference"
            android:title="@string/title_checkbox_preference"/>

    </PreferenceCategory>

    <PreferenceCategory
        android:title="@string/inline_preferences">

        <CheckBoxPreference
            android:key="checkbox_preference"
            android:summary="@string/summary_checkbox_preference"
            android:title="@string/title_checkbox_preference"/>
        <ListPreference
            android:dialogTitle="@string/dialog_title_list_preference"
            android:entries="@array/entries_list_preference"
            android:entryValues="@array/entryvalues_list_preference"
            android:key="list_preference"
            android:summary="@string/summary_list_preference"
            android:title="@string/title_list_preference"/>
    </PreferenceCategory>
</PreferenceScreen>
Copy the code

Use subscreens

Use the PreferenceCategory property to swipe the molecular screen

<? xml version="1.0" encoding="utf-8"? > <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <PreferenceCategory
        android:title="@string/inline_preferences">

        <CheckBoxPreference
            android:key="checkbox_preference"
            android:summary="@string/summary_checkbox_preference"
            android:title="@string/title_checkbox_preference"/>

    </PreferenceCategory>

    <PreferenceScreen
        android:key="button_voicemail_category_key"
        android:title="Voice mail"
        android:persistent="false">

        <CheckBoxPreference
            android:key="checkbox_preference"
            android:summary="@string/summary_checkbox_preference"
            android:title="@string/title_checkbox_preference"/>
        <ListPreference
            android:dialogTitle="@string/dialog_title_list_preference"
            android:entries="@array/entries_list_preference"
            android:entryValues="@array/entryvalues_list_preference"
            android:key="list_preference"
            android:summary="@string/summary_list_preference"
            android:title="@string/title_list_preference"/>
    </PreferenceScreen>
</PreferenceScreen>
Copy the code

Configure the intent to jump to the activity

Sometimes our Settings project does not save a configuration item, but rather jump to a new screen. We can use the following configuration to make preferences jump to a web page

<Preference android:title="@string/prefs_web_page" >
    <intent android:action="android.intent.action.VIEW"
            android:data="http://www.example.com" />
</Preference>
Copy the code

Of course, you can also configure an explicit intent to jump, as described in the official documentation. You can set a default value to the Preference control

<! -- default value is a boolean --> <CheckBoxPreference android:defaultValue="true"
    ... />

<!-- default value is a string -->
<ListPreference
    android:defaultValue="@string/pref_syncConnectionTypes_default". />Copy the code

Can be called on the enter Settings page

PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);
Copy the code

The most common use of this interface is to restore the Settings to initialize the default values.

Use the preference header

There is often a need to click on a preference to jump to another screen. This can also be done with PreferenceScreen, but using PreferenceScreen doesn’t work with tablets in cases like the one below

To achieve this effect, use Hearders

<? xml version="1.0" encoding="utf-8"? > <preference-headers xmlns:android="http://schemas.android.com/apk/res/android">
    <header
        android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentOne"
        android:title="@string/prefs_category_one"
        android:summary="@string/prefs_summ_category_one" />
    <header
        android:fragment="com.example.prefs.SettingsActivity$SettingsFragmentTwo"
        android:title="@string/prefs_category_two"
        android:summary="@string/prefs_summ_category_two"> <! -- key/value pairs can be included as argumentsfor the fragment. -->
        <extra android:name="someKey" android:value="someHeaderValue" />
    </header>
</preference-headers>
Copy the code

Android :fragment is used to mark the fragment after clicking, and extra is used to pass parameters. You can get bundle data passed in the Fragment via getArguments(). The best part of this data is to load different Preference XML in the same Fragment.

public static class SettingsFragment extends PreferenceFragment {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String settings = getArguments().getString("settings");
        if ("notifications".equals(settings)) {
            addPreferencesFromResource(R.xml.settings_wifi);
        } else if ("sync".equals(settings)) { addPreferencesFromResource(R.xml.settings_sync); }}}Copy the code

To display the contents of this header file you need to override the onBuildHeaders method.

public class SettingsActivity extends PreferenceActivity { @Override public void onBuildHeaders(List<Header> target) { loadHeadersFromResource(R.xml.preference_headers, target); }}Copy the code

The preference-headers tag can only support versions later than 3.0. To be compatible with versions earlier than 3.0, you need to write another XML for compatibility

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <Preference
        android:title="@string/prefs_category_one"
        android:summary="@string/prefs_summ_category_one"  >
        <intent
            android:targetPackage="com.example.prefs"
            android:targetClass="com.example.prefs.SettingsActivity"
            android:action="com.example.prefs.PREFS_ONE" />
    </Preference>
    <Preference
        android:title="@string/prefs_category_two"
        android:summary="@string/prefs_summ_category_two" >
        <intent
            android:targetPackage="com.example.prefs"
            android:targetClass="com.example.prefs.SettingsActivity"
            android:action="com.example.prefs.PREFS_TWO" />
    </Preference>
</PreferenceScreen>
Copy the code

Load again as follows

@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); .if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
        // Load the legacy preferences headers
        addPreferencesFromResource(R.xml.preference_headers_legacy);
    }
}

// Called only on Honeycomb and later
@Override
public void onBuildHeaders(List<Header> target) {
   loadHeadersFromResource(R.xml.preference_headers, target);
}
Copy the code

The onBuildHeaders callback will only be called on builds. Version_codes. HONEYCOMB (OS 3.0) and above. Also we must pay attention to the point, the current preferences won’t you call the registerOnSharedPreferenceChangeListener () storage strong reference to the listener. However, you must store a strong reference to the listener, or it could easily be garbage collected. The above is about how to use the system to provide a UI control with Preference function to create a Settings interface.