我有一个使用用户位置的应用程序。我有一个对话框(如下图所示),要求用户允许“允许”或“禁止”应用程序使用用户的位置(用户在安装后第一次打开应用程序或用户尝试使用基于位置的服务时弹出对话框使用用户位置是“禁止” - 由用户使用)。
我还在PreferenceActivity
中使用偏好项目(复选框)(下图),用户可以在其中切换他的偏好。
要更改共享偏好的值,我已使用此代码
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)?
答案 0 :(得分:4)
使用
解决了这个问题
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
而不是
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
答案 1 :(得分:1)
您可以在addPreferencesFromResource
的{{1}}中致电onCreate
,以便从首选项中填充您的用户界面。
另外,您可能需要确保PreferenceActivity
的XML定义中包含CheckBoxPreference
。