开发者

Updating preferences in real time

开发者 https://www.devze.com 2023-04-09 04:52 出处:网络
I have a Preferences Screen which has some prefs that are interconnected. Which means, if I have pref x and y, I sometimes need y to change to something when x changes.

I have a Preferences Screen which has some prefs that are interconnected. Which means, if I have pref x and y, I sometimes need y to change to something when x changes.

What I'm doing at the moment is listening to prefs change event, and do this:

SharedPreferences.Editor editor = prefs.edit();
editor.putString("y_pref", "somevalue");
editor.commit();

The problem is, that to actually see the change I have to first close the prefs screen and then open it again, only that way will I see the newly 开发者_Go百科set prefs.

Is there a way to change the prefs so that the change is visible right away, without the need to reload the prefs screen?


Try to call the setter of the preference itself instead updating it on your own:

E.g. EditTextPreference.setText(). So the preference itself updates it's own value too. If you do the update on your own the preference will not fetch the new value because it doesn't even know that the persisted value has changed.

If you have a PreferenceFragment, you can get the preference with PreferenceFragment.findPreference().

If you have a PreferenceActivity, you can get the preference with PreferenceActivity.findPreference().

You call that with the preference key you assigned in your settings XML file and you get an instance of the corresponding preference. Then you cast it to an CheckBoxPreference, EditTextPreference, etc (the type you set in your XML file).

0

精彩评论

暂无评论...
验证码 换一张
取 消