4ntoine 4ntoine - 5 months ago 598
Android Question

How to determine when Fragment becomes visible in 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
onResume()
event is fired in the second fragment long after it becomes actually visible. That's why I'm trying to find an event which fires when the second fragment becomes really visible to show a dialog at the appropriate moment.

How can this be done?

Answer

UPDATE: Android Support Library (rev 11) finally fixed the user visible hint issue, now if you use support library for fragments, then you can safely use getUserVisibleHint() or override setUserVisibleHint() to capture the changes as described by gorn's answer.


The outdated answer:

In most use cases, ViewPager only show one page at a time, but the pre-cached fragments are also put to "visible" state (actually invisible) if you are using FragmentStatePagerAdapter in Android Support Library pre-r11.

I override :

public class MyFragment extends Fragment {
    @Override
    public void setMenuVisibility(final boolean visible) {
        super.setMenuVisibility(visible);
        if (visible) {
            // ...
        }
    }
   // ...
}

To capture the focus state of fragment, which I think is the most suitable state of the "visibility" you mean, since only one fragment in ViewPager can actually place its menu items together with parent activity's items.

Comments