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?
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.
onStart()The onStart() method is called once the fragment gets visible.
1 Answer. Show activity on this post. You cannot do that, the viewpager requires at least one fragment to the left and one to the right. I suggest you move the onResume() logic to a separate method and call it when the fragment becomes visible.
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 { } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With