update preferences values after changing them programatically

微笑、不失礼 提交于 2019-12-24 08:49:23

问题


i've got a simple PreferenceActivity.
in my activity im using the values stored in those keys.
through getDefaultSharedPreferences and getBoolean("somekey")

if i now change the preference associated with "somekey", everything works fine and
the getBoolean returns the right value.

but if i set the value "somekey" to another value programatically,
via Preferences.Editor the settings view doesn't update to the new value! like this:

pref_edit.putBoolean("somekey", true);
pref_edit.commit();

if "somekey" was true before, and i now get the value via getBoolean("somekey");
it is true like what i changed it to, but the checkbox inside the preferences misses this change.
why? how can i update the preferences view?


回答1:


Well, valid question and it's not an easy one - some people say finish, some others say

setPreferenceScreen(null);
addPreferencesFromResource(R.xml.preferences);

and what I ended up doing to avoid such measures and the mess they cause on tablets and the like is to register an SharedPreferences.OnSharedPreferenceChangeListener (make my preferences activity into one that is) and when I detect a change in the preferences to update my checkbox (if its value disagrees with the stored preference - so it was not changed manually, cause if changed manually I have an onClick which changes the default shared preferences). Annoying indeed.



来源:https://stackoverflow.com/questions/21171530/update-preferences-values-after-changing-them-programatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!