- Retrieving and Reading Shared Preferences
- Storing and Updating Shared Preferences
- Creating Preferences Resources Files
- Using the <em>PreferenceActivity</em> Class
Creating Preferences Resources Files
Now that you know how to store and retrieve application preferences programmatically, let's move on to creating a consistent, user-friendly user interface to manage them. Let’s say you want your application to allow its user to see and edit the preference values directly. As mentioned earlier, the Android SDK provides a straightforward mechanism for especially this purpose.
The first step is to create an XML resource file that defines which preferences you will allow the user to edit. A preference resource file contains a root level <PreferenceScreen> tag, followed by various preference types that can be organized into categories. The types include preferences for checkboxes, which store Boolean values; EditText controls, which store a String type; and list preferences for selecting among a list of items (much like a drop-down). Preferences each have a title and some summary text that will be displayed to the user. Use these fields to tell the user what each preference is, and how it works. Although these strings can come from a resource value (making preference resource files localizable), we'll directly put them in the file such that the XML is more readable in our example.
The following XML collects three strings and three Boolean values. The preferences are organized into two categories, with some of the items existing outside either category. This information is stored in a resource file called /res/xml/preferences.xml:
<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"> <CheckBoxPreference android:key="flag_1" android:title="Flag 1" android:summary="This flag is on by default" android:defaultValue="true" /> <EditTextPreference android:key="string_1" android:title="A String" android:summary="This is a string value" android:defaultValue="default" /> <PreferenceCategory android:title="Category 1"> <CheckBoxPreference android:key="flag_2" android:title="Flag 2" android:summary="This flag is off by default" android:defaultValue="false" /> <EditTextPreference android:key="string_2" android:title="Another String" android:summary="This is also a string value" android:defaultValue="some value" /> </PreferenceCategory> <PreferenceCategory android:title="Category 2"> <CheckBoxPreference android:key="flag_3" android:title="Flag 3" android:summary="This flag is on by default" android:defaultValue="true" /> <EditTextPreference android:key="string_3" android:title="Yet another String" android:summary="Write something" android:defaultValue="Something" /> </PreferenceCategory> </PreferenceScreen>
That’s all you need to do in your preference resource file. However, you can't yet see it in action until you link it up with a PreferencesActivity class.