为了创建和修改一个Shared Preference,在程序上下文中调用getSharedPreferences方法,传入你要变更的Shared Preference的名字。Shared Preference可以在程序的组件间共享,但对其它应用程序来说不可获得的。
修改一个Shared Preference,使用SharedPreferences.Editor类。通过对你想要改变的SharedPreference对象调用edit方法获得Editor对象。保存修改的结果时,调用Editor的commit方法。如下面的代码片段所示:
public static final String MYPREFS = “mySharedPreferences”;
protected void savePreferences()
{
// Create or retrieve the shared preference object.
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences = getSharedPreferences(MYPREFS, mode);
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = mySharedPreferences.edit();
// Store new primitive types in the shared preferences object.
editor.putBoolean(“isTrue”, true);
editor.putFloat(“lastFloat”, 1f);
editor.putInt(“wholeNumber”, 2);
editor.putLong(“aNumber”, 3l);
editor.putString(“textEntryValue”, “Not Empty”);
// Commit the changes.
editor.commit();
}