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

AndroidUser InterfaceAndroid FragmentsAndroid Viewpager

Android Problem Overview


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)

Android Solutions


Solution 1 - Android

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

Solution 2 - Android

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.

Solution 3 - Android

For my purposes, it worked to use ViewPager.OnPageChangeListener.onPageSelected() in conjunction with Fragment.onActivityCreated() to perform an action when the Fragment is visible. Fragment.getUserVisibleHint() helps too.

Solution 4 - Android

I'm using "setMenuVisibility"-Method for resolving this Problem. As every Fragment can have actionbar-items this is the part where you can determine which Fragment is currently visible to the user.

@Override
public void setMenuVisibility(final boolean visible) {
    super.setMenuVisibility(visible);
    if (!visible) {
        //not visible anymore
    }else{
        yay visible to the user
    }
}

Solution 5 - Android

What is wrong with using getView().isShown() to find out if a Fragment is actually visible?

Solution 6 - Android

isVisible() 

Can still return true even if the fragment is behind an activity.

I'm using the following:

if (getView() != null && getView().isShown()) {
//your code here
}

Solution 7 - Android

If you know what "page" each fragment is attached to you could use ViewPager.getCurrentItem() to determine which fragment is "visible".

Solution 8 - Android

In my case i a have to do some work on the first fragment when the fragment is visible to the user

 @Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);


    if(viewPager.getAdapter() instanceof YourPager)
    {
        Fragment fragemnt=((YourPager)viewPager.getAdapter()).getFragment(0); //getFragment(int index) custom method
        if( fragemnt instanceof YourFragment)
        {
            ((YourFragment)fragemnt).methodWhochShouldBeCalledAfterUIVisible();
        }
    }
}

Solution 9 - Android

setUserVisibleHint probably may not be called, onHiddenChanged may be called not every time when another fragment is being closed. So, you may rely on onResume (and onPause), but it is usually called too often (for example, when you turn on a device screen). Also in some situations it is not called, you should manage current fragment in host activity and write:

if (currentFragment != null) {
	currentFragment.onResume();
}

Solution 10 - Android

Kotlin:

if (userVisibleHint) {
    // the fragment is visible
} else {
    // the fragment is not visible
}

Java

if (getUserVisibleHint()) {
    // the fragment is visible
} else {
    // the fragment is not visible
}

https://developer.android.com/reference/android/app/Fragment.html#getUserVisibleHint()

https://stackoverflow.com/a/12523627/2069407

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDavid S.View Question on Stackoverflow
Solution 1 - AndroidmiroslavignView Answer on Stackoverflow
Solution 2 - AndroidhcplView Answer on Stackoverflow
Solution 3 - AndroidLeo LandauView Answer on Stackoverflow
Solution 4 - AndroidFrame91View Answer on Stackoverflow
Solution 5 - AndroidawyView Answer on Stackoverflow
Solution 6 - AndroidvvbYWf0ugJOGNA3ACVxpView Answer on Stackoverflow
Solution 7 - AndroidroflharrisonView Answer on Stackoverflow
Solution 8 - AndroidW00diView Answer on Stackoverflow
Solution 9 - AndroidCoolMindView Answer on Stackoverflow
Solution 10 - Androids-hunterView Answer on Stackoverflow