实时更新首选项 [英] Updating preferences in real time

查看:45
本文介绍了实时更新首选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个首选项屏幕,其中有一些相互关联的首选项.这意味着,如果我有偏好 xy,我有时需要 yx 更改时更改为某些内容.

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?

推荐答案

尝试调用首选项本身的设置器,而不是自己更新它:

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

例如EditTextPreference.setText().所以偏好本身也会更新它自己的值.如果您自己进行更新,首选项将不会获取新值,因为它甚至不知道持久值已更改.

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,您可以使用 PreferenceFragment.findPreference().

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

如果你有一个 PreferenceActivity,你可以通过 PreferenceActivity.findPreference().

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

您使用在设置 XML 文件中分配的首选项键调用它,然后您将获得相应首选项的实例.然后将其转换为 CheckBoxPreferenceEditTextPreference 等(您在 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).

这篇关于实时更新首选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆