更改 Android 中 SharedPreferences 中的值后更新首选项屏幕中的复选框值
我有一个使用用户位置的应用程序。我有一个对话框(下图)询问用户是否允许“允许”或“禁止”应用程序使用用户的位置(用户安装后第一次打开应用程序时或当用户尝试使用基于位置的服务时会弹出对话框)使用用户位置是用户“禁止”的)。
我也使用偏好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)?
I have an app which uses the user's location. I have a dialog(pic below) asking user's permission to "Allow" or "Disallow" the app to use the user's location ( dialog pops up the first time users opens the app after installation OR when user tries to use the location based service while using user location is "Disallow"-ed by the user).
I also use preference item(a checkbox)(pic below) in PreferenceActivity
where the user can the toggle his preference.
To change the value of the sharedpreference I have use this code
public void onClick(DialogInterface dialog, int id)
{
sharedPrefs =getSharedPreferences("prefs",MODE_WORLD_WRITEABLE);
Editor editor = sharedPrefs.edit();
editor.putBoolean("locationPermission", true);
editor.commit();
}
I had expected the checkbox value to change automatically depending on the dialog selection as the key "locationPermission" holds the value to the checkbox. But it is not so.
Now how do I map the dialog(pic 1) selection to the checkbox value(pic 2)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
该问题已通过使用
解决
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
而不是
sharedPrefs = getSharedPreferences("prefs", MODE_WORLD_WRITEABLE);
The issue was solved by using
sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
instead of
sharedPrefs = getSharedPreferences("prefs", MODE_WORLD_WRITEABLE);
您可以在
PreferenceActivity
的onCreate
中调用addPreferencesFromResource
,以便根据首选项填充您的 UI。另外,您可能需要确保您的
CheckBoxPreference
在其 XML 定义中具有android:persistent-"true"
。You can call
addPreferencesFromResource
in theonCreate
of yourPreferenceActivity
so that your UI is populated from the preferences.Also, you may want to make sure that your
CheckBoxPreference
hasandroid:persistent-"true"
in its XML definition.