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

David S. picture David S. · Feb 17, 2012 · Viewed 59k times · Source

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)

Answer

miroslavign picture miroslavign · Sep 25, 2012

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");
    }
}