片段的生命周期如何在viewpager中工作?为什么导航更改时不调用onStop? [英] How does fragment's lifecycle works inside viewpager? Why onStop is not called on navigation change?

查看:91
本文介绍了片段的生命周期如何在viewpager中工作?为什么导航更改时不调用onStop?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将AndroidX中的ViewPager 2与4个相同片段的实例一起使用.我的问题很简单.当我导航到另一个片段时(使用导航抽屉或什至其他东西). viewpager中的片段的OnStop(),OnDestroy(),OnDettach()不会被触发.那为什么呢?而且,如果我想删除已经开始的监听器,可以使用其中一种方法来做到这一点?

I'm using ViewPager 2 from AndroidX with 4 instances of the same fragment. My question is pretty straight forward. When I'm navigating to some another fragment(using navigation drawer or even something else). OnStop() , OnDestroy(), OnDettach() of the fragments inside the viewpager does not gets triggered. So why is that? And If I want to remove the listeners I've started already, in one of these methods, how can I do that?

例如,我正在使用GreenRobot的EventBus.而且我正在OnStart内部注册EvenBus:

For example, I'm using GreenRobot's EventBus. And I'm registering the EvenBus inside OnStart:

override fun onStart() {
    super.onStart()
    EventBus.getDefault().register(this)
}

并从OnStop删除它:

And Removing it from OnStop:

override fun onStop() {
    Log.e(TAG, "onStop: ")
    EventBus.getDefault().unregister(this)
    super.onStop()
}

但是如上所述,当我离开viewpager时,onStop不会触发.我什至通过登录进行了检查.

But when I navigate away from the viewpager as I explained above, onStop does not trigger. I even checked it by logging.

那么片段生命周期与viewpager的工作原理不同吗?如果是的话,我该如何解决这个问题(注销EvetBus).

So is the fragment lifecycle works differently with viewpager? And if yes, how can I overcome this problem(unregistering EvetBus).

推荐答案

不幸的是,当涉及到ViewPager和其中的Fragments时,EventBus并没有提供很大的用处.

Unfortunately, EventBus does not provide great usefulness when it comes to ViewPager and Fragments inside it.

尽管我找到了解决方案,但使用了更传统的方法:接口

Though I found a solution, using the more traditional approach: Interfaces

它不能直接回答问题为什么导航更改时未调用onStop on ViewPager内部的片段?

但是当将EvenBus与ViewPager一起使用时,它的确可以将您从多个事件触发器中拯救出来.使用接口,您不必显式注销接口.是否调用onStop无关紧要.

But it does save you from multiple Event triggers when using EvenBus with ViewPager. With interfaces, As you don't have to explicitly unregister the interface. It does not matter if the onStop is called.

这篇关于片段的生命周期如何在viewpager中工作?为什么导航更改时不调用onStop?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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