Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a fragment view is visible to the user?

I have a ViewPager, each page is a Fragment view. I want to test if a fragment is in a visible region. the Fragment.isVisible only test

  • the fragment is attached to a activity
  • the fragment is set to visible
  • the fragment has been added to a view

The ViewPager will create 3 (by default) fragment and all three of them meet the above criteria, but only one is actually visible to the user (the human eyes)

like image 228
David S. Avatar asked Feb 17 '12 05:02

David S.


People also ask

How do you check if a fragment is visible or not?

Adding some information here that I experienced: fragment. isVisible is only working ( true/false ) when you replaceFragment() otherwise if you work with addFragment() , isVisible always returns true whether the fragment is in behind of some other fragment.

Which method is called once the fragment gets visible?

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

Which method is used to access the fragmented view?

onStart() makes the fragment visible to the user (based on its containing activity being started). onResume() makes the fragment begin interacting with the user (based on its containing activity being resumed).


2 Answers

This is what I use to determine the visibility of a fragment.

private static boolean m_iAmVisible;  @Override public void setUserVisibleHint(boolean isVisibleToUser) {      super.setUserVisibleHint(isVisibleToUser);     m_iAmVisible = isVisibleToUser;      if (m_iAmVisible) {          Log.d(localTAG, "this fragment is now visible");     } else {           Log.d(localTAG, "this fragment is now invisible");     } } 
like image 193
miroslavign Avatar answered Sep 30 '22 17:09

miroslavign


You're right there is a better way to do this!

Have a look at the FragmentPagerAdapter javadoc online and you'll see there is a method setPrimaryItem(ViewGroup container, int position, Object object):void doing exactly what you need.

From the javadoc

public void setPrimaryItem (ViewGroup container, int position, Object object)

Called to inform the adapter of which item is currently considered to be the "primary", that is the one show to the user as the current page.

Parameters container The containing View from which the page will be removed. position The page position that is now the primary. object The same object that was returned by instantiateItem(View, int).

Note on scroll state

Now if you implement this and start debugging to get a feel of when exactly this is called you'll quickly notice this is triggered several times on preparing the fragment and while the user is swiping along.

So it might be a good idea to also attach a ViewPager.OnPageChangeListener and only do what has to be done once the viewpagers scroll state becomes SCOLL_STATE_IDLE again.

like image 30
hcpl Avatar answered Sep 30 '22 16:09

hcpl