Preferences are Androids encapsulation of behavior for setting and saving (exposed) global state for an application. Here are the parts which are needed:
- Preferences xml file
- Located not in layouts, but in res/xml directory.
- Preferences are contained within root node of PreferenceScreen type.
- String resources
- string
- string-array
- PreferenceFragment
- PreferenceActivity
- AndroidManifest
- Add preferences activity
- Initializing default values
- Set in XML
- android:defaultValue="value", where value is a string or @string/id
- In main onCreate method and any other activity the user can enter into application
PreferenceActivity: Post Android 3.0
The activity instantiating the PreferenceFragment has to use a PreferenceFragment, but it can be any Activity, not a PreferenceActivity. The code below attaches a fragment, from Google's Android Docs:
The activity instantiating the PreferenceFragment has to use a PreferenceFragment, but it can be any Activity, not a PreferenceActivity. The code below attaches a fragment, from Google's Android Docs:
public class SettingsActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Display the fragment as the main content. getFragmentManager().beginTransaction() .replace(android.R.id.content, new SettingsFragment()) .commit(); } }
Version 3.0 and Older
Android docs show the following code to instantiate a PreferenceFragment before version 3.0, pay attention to which version you're developing for, because on version 3.0 and higher, addPreferences is deprecated.
public class SettingsActivity extends PreferenceActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState);addPreferencesFromResource(R.xml.preferences); // DEPRECATED IN >= 3.0 } }
PreferenceFragment
addPreferencesFromResource in PreferenceFragment is not deprecated.
public static class SettingsFragment extends PreferenceFragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Load the preferences from an XML resource addPreferencesFromResource(R.xml.preferences); } ... }Initializing Default Values
Call the following from onCreate of main application activity to make sure default preferences are initialized. Note, that passing false in the third argument prevents overwriting any modifications to preference values, so it's safe to call in onCreate every time the app starts:
PreferenceManager.setDefaultValues(this, R.xml.advanced_preferences, false);
Preferences XML
Types of preferences are:
- Category
- PreferenceScreen
- Must be root category.
- Subsequent declarations create a screen break.
- PreferenceCategory
- Preference
- Creates subcategory
- Types
- CheckBoxPreference
- ListPreference
- EditTextPreference
- Intent
- RingtonePreference
- headers
- more detail coming