Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 357
4ntoine Avatar asked Apr 05 '12 07:04

4ntoine


People also ask

How do you know when a fragment becomes visible?

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.

Which method is called once the fragments gets visible?

onStart()The onStart() method is called once the fragment gets visible.

How do you make a ViewPager only resume selected fragment?

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.


1 Answers

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 {         }     } } 
like image 97
gorn Avatar answered Oct 09 '22 05:10

gorn