实时更新偏好设置
我有一个首选项屏幕,其中有一些相互关联的首选项。这意味着,如果我有 pref x
和 y
,有时需要在 x
更改时将 y
更改为某些内容。
我现在正在做的是监听首选项更改事件,然后执行以下操作:
SharedPreferences.Editor editor = prefs.edit();
editor.putString("y_pref", "somevalue");
editor.commit();
问题是,要真正看到更改,我必须首先关闭首选项屏幕,然后再次打开它,只有这样我才能看到新设置的首选项。
有没有办法更改首选项,以便更改立即可见,而无需重新加载首选项屏幕?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试调用首选项本身的设置器,而不是自行更新它:
例如 EditTextPreference< /a>.setText()。所以偏好本身也会更新它自己的价值。如果您自己进行更新,首选项将不会获取新值,因为它甚至不知道持久值已更改。
如果您有
PreferenceFragment
,则可以使用 PreferenceFragment.findPreference()。如果您有
PreferenceActivity
,则可以使用 PreferenceActivity.findPreference()。您可以使用在设置 XML 文件中分配的首选项键来调用它,并获得相应首选项的实例。然后将其转换为
CheckBoxPreference
、EditTextPreference
等(您在 XML 文件中设置的类型)。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).