2

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

首选项.xml 是这样的:

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

<PreferenceCategory android:title="Patient&apos;s Settings" >
    <EditTextPreference
        android:defaultValue="Not Set"
        android:key="patientMobile"
        android:title="mobile number" />
</PreferenceCategory>
<PreferenceCategory android:title="Doctor&apos;s Settings" >
    <EditTextPreference
        android:defaultValue="Not Set"
        android:key="docEmail"
        android:title="e-mail" />
    <EditTextPreference
        android:defaultValue="Not Set"
        android:key="docMobile"
        android:title="mobile number" />
</PreferenceCategory>
<PreferenceCategory android:title="Application Settings" >
    <SwitchPreference
        android:disableDependentsState="false"
        android:enabled="true"
        android:key="lang"
        android:summaryOff="English"
        android:summaryOn="Greek"
        android:switchTextOff="EN"
        android:switchTextOn="GR" />
</PreferenceCategory>

我如何从另一个活动中设置/更新/覆盖这些值?

我从 web 服务中检索信息,然后我想保存这些值,然后从 SettingsActivity 中看到:

1.patientMobile (string)
2.docEmail      (string)
3.docMobile     (string)
4

2 回答 2

4

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

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();
于 2012-08-24T11:05:44.557 回答
0

当您检索值时,您将它们保存为:

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);

请参阅应用()。还有SharedPreferences文档。

于 2012-08-24T11:15:11.930 回答