简体   繁体   English

如何监听片段中的首选项更改?

[英]How to listen for a preference change in a fragment?

Lots of similar questions but I still can't find an answer. 很多类似的问题,但我仍然找不到答案。 So I have a Fragment where I want to listen for changes in a PreferenceActivity . 所以我有一个片段,我想听取PreferenceActivity变化。

The documentation says to register the listener in onResume() and un-register in onPause() : 文档说在onResume()注册监听器并在onPause()取消注册:

For proper lifecycle management in the activity, we recommend that you register and unregister your SharedPreferences.OnSharedPreferenceChangeListener during the onResume() and onPause() callbacks, respectively: 为了在活动中进行适当的生命周期管理,我们建议您分别在onResume()和onPause()回调期间注册和注销SharedPreferences.OnSharedPreferenceChangeListener:

I assume they are referring to registering the listener from within the PreferenceActivity onResume/onPause methods, since if you unregister the listener in the Fragment's onPause() , then it will not listen for the changes. 我假设它们指的是在PreferenceActivity onResume/onPause方法中注册监听器,因为如果你在Fragment的onPause()取消注册监听器,那么它将不会监听这些更改。

So is the solution to do the opposite ie - register in onPause() and un-register in onResume() ? 那么相反的解决方案是 - 在onPause()注册并在onResume()取消注册?

Thanks! 谢谢!

It's not the PreferenceActivity that notify the changes on the preferences but the SharedPreferences it's self. PreferenceActivity不是通知首选项的更改,而是它自己的SharedPreferences The PreferenceActivity is a meare user interface to access the SharedPreferences . PreferenceActivity是用于访问SharedPreferences的meare用户界面。

So if it's your fragment that needs to listen for SharedPreferences changes it should be the one to register for changes. 因此,如果您的片段需要监听SharedPreferences更改,则应该注册更改。 In other words let your fragment implement the OnSharedPreferenceChangeListener and register for this changes on the fragment onResume and unregister onPause as the doc say. 换句话说,让你的片段实现OnSharedPreferenceChangeListener并在片段onResume上注册这些更改,并按照文档说明取消注册onPause

You also need to load the preference on the fragment onResume so when it goes onPause then onResume the current state of the preference is loaded. 您还需要在片段onResume上加载首选项,这样当它继续onPause然后onResume时,将加载首选项的当前状态。

See also https://stackoverflow.com/a/13596569/665823 另请参见https://stackoverflow.com/a/13596569/665823

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM