When there’s no limit to what Android gets, there’s no limit to what Android does
Add settings to an application using Preferences
You can use Preference classes from Android SDK to store, set and retrieve Settings at application level or at activity level.
There are 2 ways to manipulate preferences :
- Using your own screen to modify the settings
- Using the built in PreferenceActivity class
Let’s take a look :
Part 1. Use your own screen
- Create your own screen using layouts
- Define a name for preference file
- Restore preferences
-
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
-
boolean silent = settings.getBoolean("silentMode", false);
-
- Edit preference
-
//We need an Editor object to make preference changes.
-
// All objects are from android.context.Context
-
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
-
SharedPreferences.Editor editor = settings.edit();
-
editor.putBoolean("silentMode", mSilentMode);
-
- Commit the edits!
-
editor.commit();
-
-
-
If you want to store preference only for current activity use getPreferences(mode)
-
Part 2 : Use PreferenceActivity
- Create a class that extends PreferenceActivity : public class Preferences extends PreferenceActivity
- Create a xml file that contain Preference screen layout
-
-
- There are many available fields : CheckBoxPreference, EditTextPreference, RingtonePreference, ListPreferenceIf you want to open a new screen for specific preferences you can wrap them in a PreferenceScreen tag.
- Find preference by key :
-
mListMeasurementUnits = (ListPreference)getPreferenceScreen().findPreference(KEY_LIST_MEASUREMENTUNITS);
-
- If you want to show changes in the preferences screen, you may use :
-
public class Preferences extends PreferenceActivity implements OnSharedPreferenceChangeListener
-
mListMeasurementUnits.setSummary("Current value is : " + sharedPreferences.getString(key, "Not set") );
-
}
-
-
@Override
-
protected void onPause() {
-
// Unregister the listener whenever a key changes
-
getPreferenceScreen().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
-
-
super.onPause();
-
}
-
-
@Override
-
protected void onResume() {
-
-
// Set up a listener whenever a key changes
-
sharedPreferences.registerOnSharedPreferenceChangeListener(this);
-
-
super.onResume();
-
}
-
- Retrieve settings from any activity or service that run in the same context as PreferenceActivity
-
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
-
Source : http://developer.android.com/guide/topics/data/data-storage.html#pref
Print article | This entry was posted by Sebastian on 2010/07/10 at 21:29, and is filed under Android development. Follow any responses to this post through RSS 2.0. Both comments and pings are currently closed. |
Comments are closed.