Android - Settings (Preference)

> Android

1 - About

Settings (UI Preference or Parameters) allow users to modify app features and behaviors and are implemented through the Android's Preference APIs

See also Android - Shared Preference

Advertising

3 - Management

3.1 - Build

Instead of using View objects to build the user interface, settings are built using various subclasses of the Preference class that you declare in an XML file.

A Preference object is the building block for a single setting. Each Preference appears as an item in a list and provides the appropriate UI for users to modify the setting.

For example:

  • a CheckBoxPreference creates a list item that shows a checkbox,
  • a ListPreference creates an item that opens a dialog with a list of choices.

Because your app's settings UI is built using Preference objects instead of View objects, you need to use a specialized Activity or Fragment subclass to display the list settings:

  • For Android older than 3.0 (API level 10 and lower), you must build the activity as an extension of the PreferenceActivity class.
  • For Android 3.0 and later, you should instead use:
    • a traditional Activity that hosts a PreferenceFragment (Displays a hierarchy of Preference objects as a list, similar to PreferenceActivity.)
    • or a PreferenceActivity to create a two-pane layout for large screens when you have multiple groups of settings.

Example: In pref_general.xml, a new CheckBox preference:

<CheckBoxPreference
 android:title="@string/pref_enable_notifications_label"
 android:key="@string/pref_enable_notifications_key"
 android:summaryOff="@string/pref_enable_notifications_false"
 android:summaryOn="@string/pref_enable_notifications_true"
 android:defaultValue="@string/pref_enable_notifications_default" />
Advertising

3.2 - Get

Each added Preference has a corresponding key-value pair that the system uses to save the setting in a default SharedPreferences file for your app's settings.

The only time interact with the associated SharedPreferences file is when you need to read a value.

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
String string = sharedPref.getString(getString(R.string.pref_key),getString(R.string.pref_default));

4 - Documentation / Reference