更改Android中SharedPreferences中的值后,更新首选项屏幕中的复选框值

时间:2011-12-05 11:08:58

标签: android android-preferences android-dialog


我有一个使用用户位置的应用程序。我有一个对话框(如下图所示),要求用户允许“允许”或“禁止”应用程序使用用户的位置(用户在安装后第一次打开应用程序或用户尝试使用基于位置的服务时弹出对话框使用用户位置是“禁止” - 由用户使用)。
dialog

我还在PreferenceActivity中使用偏好项目(复选框)(下图),用户可以在其中切换他的偏好。
prefs item

要更改共享偏好的值,我已使用此代码

    public void onClick(DialogInterface dialog, int id)
    {
        sharedPrefs =getSharedPreferences("prefs",MODE_WORLD_WRITEABLE);
        Editor editor = sharedPrefs.edit();
        editor.putBoolean("locationPermission", true);
        editor.commit();
}

我原本希望复选框值根据对话框选择自动更改,因为键“locationPermission”将值保存到复选框。但事实并非如此。

现在如何将对话框(图片1)选择映射到复选框值(图2)?

2 个答案:

答案 0 :(得分:4)

使用

解决了这个问题 sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

而不是

sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

答案 1 :(得分:1)

您可以在addPreferencesFromResource的{​​{1}}中致电onCreate,以便从首选项中填充您的用户界面。 另外,您可能需要确保PreferenceActivity的XML定义中包含CheckBoxPreference