更新preferences实时实时、preferences

2023-09-12 10:29:07 作者:⒈⒉3莣鋽祢

我有一个preferences屏幕,具有一定的preFS是相互关联的。这意味着,如果我有preF X ,我有时需要ÿ 来改变,当 X 改变一些东西。

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.

我在做什么,此刻正在听preFS变化事件,做到这一点:

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();

的问题是,真正看到的变化我必须先关闭preFS屏幕,然后再次打开它,只有这样,我会看到新设置的preFS。

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.

有没有办法改变preFS,这样的变化是明显的向右走,无需重新加载$ ​​P $ PFS屏?

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

推荐答案

尝试调用的preference本身的制定者,而不是你自己的更新吧:

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

例如。 的EditText preference 。的setText()。所以preference本身更新它自己的价值了。如果你做你自己的更新preference不会获取新的价值,因为它甚至不知道,持久的价值发生了变化。

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.

如果你有一个 preferenceFragment ,就可以得到preference与 preferenceFragment.find preference()。

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

如果你有一个 preferenceActivity ,就可以得到preference与 preferenceActivity.find preference()。

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

您打电话,与preference关键在你设置的XML文件中指定,你会得到相应的preference一个实例。然后你将它转换到复选框preference 的EditText preference 等(设置的类型在XML文件中)。

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