How does fragment's lifecycle works inside viewpager? Why onStop is not called on navigation change?

被刻印的时光 ゝ 提交于 2020-04-16 05:42:38

问题


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?

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)
}

And Removing it from OnStop:

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

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

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


回答1:


You can use setUserVisibleHint to check the fragment visibility.

  override fun setUserVisibleHint(isVisibleToUser: Boolean) {
    super.setUserVisibleHint(isVisibleToUser)

    if (isVisibleToUser) {

       //Fragment is visible

    } else {

       //Fragment is invisible
    }
}

Hope this helps.




回答2:


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

It does not directly answer the question Why onStop is not called of fragments inside ViewPager on navigation change?

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.



来源:https://stackoverflow.com/questions/58845042/how-does-fragments-lifecycle-works-inside-viewpager-why-onstop-is-not-called-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!