当我更改首选项时,为什么我的 onSharedPreferenceChangeListener 会被多次调用

发布于 2024-09-03 06:54:34 字数 340 浏览 4 评论 0原文

我编写了一个带有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感悟人生的甜 2024-09-10 06:54:34

您已将 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文