当 SharedPreferences 更改时如何更新 PreferenceActivity 的内部值
我在 PreferenceActivity 中使用 Preference 来加载默认值:当单击这个特定的 Preference 时,会发生类似的情况:
private String mResetKeys = "key1,key2,key3";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor prefs_editor = prefs.edit();
for (String current_pref : mResetKeys.split(",")) {
prefs_editor.remove(current_pref);
}
prefs_editor.commit();
但是之后,相应 SharedPreference 被重置的 Preference 仍然显示旧值 - 它似乎被缓存在 Preference 中。仅当我离开 PreferenceActivity 并重新打开它时,首选项才会显示新值。
如何以编程方式更新 PreferenceActivity?
I use a Preference in a PreferenceActivity to load default values: when this specific Preference is clicked, something like this happens:
private String mResetKeys = "key1,key2,key3";
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
SharedPreferences.Editor prefs_editor = prefs.edit();
for (String current_pref : mResetKeys.split(",")) {
prefs_editor.remove(current_pref);
}
prefs_editor.commit();
But afterwards, the Preferences whose corresponding SharedPreference was reset still show the old value - it seems to be cached in the Preference. Only when I leave the PreferenceActivity and reopen it, the Preferences show the new values.
How can I update the PreferenceActivity programmatically?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我有类似的问题。这可能不是最正确的修复,但它符合我的目的。提交后,我立即调用了 Activity.recreate(); 方法。
该活动将重新启动(
onDestroy()
/onCreate()
/etc),但出于我的目的,我所需要的只是对一个首选项进行特殊处理。我使用OnPreferenceClickListener
监听特定偏好,并制作了一个警报对话框,其中包含一种警告消息和一个改变主意的选项。如果他们确实想改变主意,我会将新值提交给首选项活动,然后调用recreate()
以便更新复选框首选项。但是,我也对一种无需重新创建活动即可执行此操作的方法感兴趣......
I had a similar problem. This probably isn't the most correct fix but it worked for my purposes. Right after I did the commits, I called the
Activity.recreate();
method.The activity will restart (
onDestroy()
/onCreate()
/etc) but for my purposes all I needed was a special handling on one preference. I listened for a certain preference with anOnPreferenceClickListener
and made an alert dialog box with a kind of warning message and an option to change their mind. If they did want to change their mind, I did my commit of the new value to the preference activity and then calledrecreate()
so that the checkbox preference would be updated.However, I am also interested in a way to do this without recreating the activity...
更新首选项值而不重新加载 PreferenceActivity
来自 http://liquidlabs.ca/2011/08 /25/update-preference-value-without-reloading-preferenceactivity/
以下是如何更新目标元素的默认共享首选项值(在本例中为 EditTextPreference)
Update preference value without reloading PreferenceActivity
from http://liquidlabs.ca/2011/08/25/update-preference-value-without-reloading-preferenceactivity/
Here is how to update default shared preference value of target element (in this case EditTextPreference)