Preferences
- Introduction
- The Preferences class provides a way to store presistent key-value pairs, which
are suitable for preferences.
- Preferences are not strictly for saving "user preferences".
They can be used for any persistent data.
- There are three ways to access preferences, all of which provide a
SharedPreferences object.
- getPreferences, for activity level preferences
- getSharedPreferences, for app level preferences - you name the set of
preferences
- getDefaultSharedPreferences, to use getSharedPreferences with a
default name based on the package name.
- Given a SharedPreferences object, you can get an editor to ...
- Get and set values based on keys
- Remove and clear keys
- Commit changes
- Using SharedPreferences
- The basic sequence of things to do is
- Use the getSharedPreferences method to get a named
SharedPreferences object.
- Use the edit method to get an editor.
- Read, add, modify values
- Use the commit method to save the changes.
- Using a PreferenceFragment
- There is a PreferenceFragmentCompat class designed for working with preferences.
- The preference items are described in XML.
- EditTextPreference - free text
- CheckBoxPreference - Boolean checkbox
- ListPreference - Single select list
- PreferenceCategory - a collection of related preferences
- Preferences can also be split off into separate screens, but it has become harder to
do with the new preferences framework.
- Example
MainActivity.java
activity_main.xml
menu.xml
DataPreferencesEdit.java
DataPreferencesEditFragment.java
edit_preferences.xml
strings.xml