当我更改首选项时,为什么我的 onSharedPreferenceChangeListener 会被多次调用
我编写了一个带有 3 个选项卡的应用程序。每个选项卡都有相同的列表视图和不同的数据源。我已在 tabhost 活动中设置 SharedPreferences,但我将 onSharedPreferenceChangeListener 方法放在 listactivity 中。当我更改首选项时,我的侦听器会被调用并更新我的数据库。这一切都在起作用。但是,如果我更改选项卡 1 中的数据,它会调用我的侦听器一次。如果我更改选项卡 2 的数据,它会调用它两次,如果我更改选项卡 3 中的数据,它会调用它三次。知道为什么会这样吗?我想我可以在我的列表活动中设置我的共享首选项,这可能会避免这个问题,但我很好奇为什么我的监听器在不同的选项卡中被多次调用。
西兰花
I've written an app with 3 tabs. Each tab has the same list view with different data sources. I have setup SharedPreferences in the tabhost activity, but I put my onSharedPreferenceChangeListener method in my listactivity. When I change a preference, my listener gets called and it updates my database. This is all working. However, if I change the data in tab 1, it calls my listener once. If I change the data for tab 2 it calls it twice and if I change the data in tab 3 it calls it three times. Any idea why it works this way? I guess I could setup my shared prefs in my listactivity and that might avoid the issue, but I'm curious why my listener is called multiple times if it's in a different tab.
brockoli
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您已将 unregisterOnSharedPreferenceChangeListener() 放置在 onDestroy() 中,并且不会在所有活动重新启动时调用它。
结论是,正确的方法是将 registerOnSharedPreferenceChangeListener() 和 unregisterOnSharedPreferenceChangeListener() 分别放置在 onResume() 和 onPause() 中。
You've placed unregisterOnSharedPreferenceChangeListener() in onDestroy() and it's not called on all activity restarts.
Conclusion is that proper way to do this is to place registerOnSharedPreferenceChangeListener() and unregisterOnSharedPreferenceChangeListener() in onResume() and onPause() respectively.