1

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

Parag Pawar
  • 827
  • 3
  • 12
  • 23
  • Check this out: https://developer.android.com/reference/android/support/v4/view/ViewPager#setoffscreenpagelimit – grrigore Nov 13 '19 at 20:28
  • 2
    I know about OffscreenPageLimit, but it is irrelevant here, suppose even if I setOffscreenPageLimit to 1 and navigate away from the viewpager, onStop still won't be called. And won't be able to unregister the listener. – Parag Pawar Nov 13 '19 at 20:36
  • Are you using `FragmentPagerAdapter` or `FragmentStatePagerAdapter`? – grrigore Nov 13 '19 at 20:44
  • 1
    Neither, as I'm using ViewPager 2 from AndroidX, I'm using FragmentStateAdapter – Parag Pawar Nov 13 '19 at 20:49

2 Answers2

0

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.

Parag Pawar
  • 827
  • 3
  • 12
  • 23
-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.

GHH
  • 1,713
  • 1
  • 8
  • 21