How to determine when Fragment becomes visible in ViewPager

How to determine when Fragment becomes visible in ViewPager

2 min read
android
android-fragments
android-viewpager

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

For example, I have 2 fragments with ViewPager and FragmentPagerAdapter. The second fragment is only available for authorized users and I need to ask the user to log in when the fragment becomes visible (using an alert dialog).

BUT the ViewPager creates the second fragment when the first is visible in order to cache the second fragment and makes it visible when the user starts swiping.

So the onResume() event is fired in the second fragment long before it becomes visible. That's why I'm trying to find an event which fires when the second fragment becomes visible to show a dialog at the appropriate moment.

How can this be done?

Photo by Mark Basarab | Unsplash
2 posted solutions
608

gorn wrote:

How to determine when Fragment becomes visible in ViewPager

You can do the following by overriding setUserVisibleHint in your Fragment:

public class MyFragment extends Fragment {
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
        }
        else {
        }
    }
}
57

lukjar wrote:

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.

Submit your solution

© 2023 Dev's Feed