如何设置/更新我的首选项的值(PreferencesCitivity)?Android

如何设置/更新我的首选项的值(PreferencesCitivity)?Android,android,save,sharedpreferences,android-preferences,Android,Save,Sharedpreferences,Android Preferences,我有一个SettingsActivity(扩展PreferenceActivity),它是从preferences.xml文件(res-->xml-->preferences.xml)加载的 preferences.xml如下所示: <?xml version="1.0" encoding="utf-8"?> 您可以使用和首选项的键读取/设置/更新这些值 SharedPreferences preferences = PreferenceManager.getDefaultShar

我有一个SettingsActivity(扩展PreferenceActivity),它是从preferences.xml文件(res-->xml-->preferences.xml)加载的

preferences.xml如下所示:

<?xml version="1.0" encoding="utf-8"?>

您可以使用和首选项的键读取/设置/更新这些值

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String patientMobile = preferences.getString("patientMobile");

//or set the values. 
SharedPreferences.Editor editor = preferences.edit();
editor.putString("patientMobile", "yes"); //This is just an example, you could also put boolean, long, int or floats
editor.commit();

当您检索值时,请将其保存为:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
Editor editor = sp.edit();
editor.putString("patientMobile", patientMobile);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
    editor.apply();
} else {
    editor.commit();
}
要读取值,只需调用sp.getString(“patientMobile”,defaultValue)


看。还有文档。

如果我在MainActivity(我的菜单)上,我是如何做到的。作为上下文,我将设置Activity.class,比如:SharedReferences preferences=PreferenceManager.GetDefaultSharedReferences(SettingsActivity.class)?和另一个问题,如果patientMobile存在,它将覆盖它,如果它不存在,它将创建它?如果您处于
设置活动
(或任何
活动
服务
类,它们都将从
上下文继承),则需要将
传递给上下文。至于你的第二个问题,答案是肯定的!我不在SettingsActivity,但我想覆盖MainActivity中的一些值!那么?我把什么作为参数?正如我所说的,任何
活动
类都可以。您的主要活动扩展了
活动
对吗?
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
String patientMobile = preferences.getString("patientMobile");

//or set the values. 
SharedPreferences.Editor editor = preferences.edit();
editor.putString("patientMobile", "yes"); //This is just an example, you could also put boolean, long, int or floats
editor.commit();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(YourActivity.this);
Editor editor = sp.edit();
editor.putString("patientMobile", patientMobile);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.GINGERBREAD) {
    editor.apply();
} else {
    editor.commit();
}