为什么当我第一次打开 tabhost 的选项卡时会调用 onResume?

发布于 2024-10-08 07:35:48 字数 251 浏览 0 评论 0原文

我有一个带有一些选项卡的 tabhost,每个选项卡都实现了 onresume 方法,因为每次用户再次进入 tabhost 时,我都需要从远程数据库重新加载所有数据,而不仅仅是第一次打开它时。

好吧,它工作得很好,但问题是,当用户第一次打开选项卡时,会调用 onCreate 和 onResume 这两个方法,然后,我的应用程序两次连接到数据库以检索信息......我只想在用户第一次进入 tabhost 时调用 onCreate 。

如何避免这种罕见的问题?

I have a tabhost with some tabs, and each tab have implemented the method onresume, because I need to reload all the data from a remote database each time the user enter again in a tabhost, not only the first time he opens it.

Ok, it works nice, but the problem is that when the user opens for the first time a tab, the two methods, onCreate and onResume are called, then, my app connect two times into the database to retrieve the info.... I want only to be called onCreate when the user enter for the first time into the tabhost.

How to avoid this rare problem?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

单身情人 2024-10-15 07:35:48

正如 Activity 生命周期文档 中所述,onCreate 和 onResume 将始终两者都会在 Activity 第一次启动时被调用。返回Activity时,至少会调用onResume,但如果Android需要释放资源,可能会再次调用onCreate。

如果您需要每次返回 Activity 时都进行设置,为什么不只将逻辑放在 onResume 中呢?

As stated on the Activity lifecycle docs, onCreate and onResume will always both be called the first time an Activity is started. When going back to Activity, at least onResume will be called, but onCreate may be called again if Android needed to free up resources.

If you need the setup to occur every time you return to the activity, why not only put the logic in onResume?

眼眸印温柔 2024-10-15 07:35:48

由于选项卡的内容是活动,因此在您启动应用程序时都必须创建(并恢复)它们。

避免这种情况的一种方法是使用视图而不是活动作为选项卡内容。这样,您就只有 1 个 onCreate() 方法,因为您只有 1 个活动(TabActivity)。

Since your tabs' contents are activities, then they both have to be created (and resumed) when you start the app.

One way to avoid this, is to use views instead of activities as the tab content. That way, you only have 1 onCreate() method because you only have 1 activity (the TabActivity).

近箐 2024-10-15 07:35:48

我同意其他海报的观点,即您应该重构您的应用程序。您不能只期望将一个独立的活动粘贴到选项卡中并让一切都有意义。

话虽这么说,您可以在某处有一个标志来指示数据库是否需要初始化。在每个活动的 onResume() 中,您有类似的内容,

synchronized (MyLock.class) {
    if (!initialized) {
      initDb();
      MyLock.initialized = true;
    }
}

I agree with the other posters that you should re-factor your app. You can't just expect to stick a stand alone activity into a tab and have everything make sense.

That being said, you could have a flag somewhere that indicates if the DB needs initialization. in each activity's onResume(), you have something like,

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