How to determine when Fragment becomes visible in ViewPager

后端 未结 26 1343
心在旅途
心在旅途 2020-11-22 00:24

Problem: Fragment onResume() in ViewPager is fired before the fragment becomes actually visible.

For example, I have 2 fragments with

26条回答
  •  悲哀的现实
    2020-11-22 01:00

    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.

提交回复
热议问题