Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

android - Updating preferences in real time

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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...