Problem: Fragment onResume()
in ViewPager
is fired before the fragment becomes actually visible.
For example, I have 2 fragments with
setUserVisibleHint(boolean visible) is now deprecated So this is the correct solution
FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
In ViewPager2 and ViewPager from version androidx.fragment:fragment:1.1.0
you can just use onPause()
and onResume()
to determine which fragment is currently visible for the user. onResume()
is called when the fragment became visible and onPause
when it stops to be visible.
To enable this behavior in the first ViewPager you have to pass FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
parameter as the second argument of the FragmentPagerAdapter
constructor.