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?
Override
setPrimaryItem()
in theFragmentPagerAdapter
subclass. I use this method, and it works well.I encountered the same problem while working with
FragmentStatePagerAdapters
and 3 tabs. I had to show a Dilaog whenever the 1st tab was clicked and hide it on clicking other tabs.Overriding
setUserVisibleHint()
alone didn't help to find the current visible fragment.When clicking from 3rd tab -----> 1st tab. It triggered twice for 2nd fragment and for 1st fragment. I combined it with isResumed() method.
To detect
Fragment
inViewPager
visible, I quite sure that only usingsetUserVisibleHint
is not enough.Here is my solution for check fragment visible, invisible when first launch viewpager, switch between page, go to another activity/fragment/ background/foreground`
EXPLANATION You can check the logcat below carefully then I think you may know why this solution will work
First launch
Go to page2
Go to page3
Go to background:
Go to foreground
DEMO project here
Hope it help
I used this and it worked !
You can do the following by overriding
setUserVisibleHint
in yourFragment
:Here is another way using
onPageChangeListener
: