In ViewPager2
and ViewPager
from version androidx.fragment:fragment:1.1.0
you can just use onPause
and onResume
callbacks to determine which fragment is currently visible for the user. onResume
callback is called when fragment became visible and onPause
when it stops to be visible.
In case of ViewPager2 it is default behavior but the same behavior can be enabled for old good ViewPager
easily.
To enable this behavior in the first ViewPager you have to pass FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
parameter as second argument of FragmentPagerAdapter
constructor.
FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
Note: setUserVisibleHint()
method and FragmentPagerAdapter
constructor with one parameter are now deprecated in the new version of Fragment from android jetpack.