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?
I overrode the Count method of the associated FragmentStatePagerAdapter and have it return the total count minus the number of pages to hide:
So, if there are 3 fragments initially added to the ViewPager, and only the first 2 should be shown until some condition is met, override the page count by setting TrimmedPages to 1 and it should only show the first two pages.
This works good for pages on the end, but wont really help for ones on the beginning or middle (though there are plenty of ways of doing this).
Add following Code inside fragment