How to know if a Fragment is Visible?

you can try this way:

Fragment currentFragment = getFragmentManager().findFragmentById(R.id.fragment_container);

or

Fragment currentFragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container);

In this if, you check if currentFragment is instance of YourFragment

if (currentFragment instanceof YourFragment) {
     Log.v(TAG, "your Fragment is Visible");
}

If you want to know when use is looking at the fragment you should use

yourFragment.isResumed()

instead of

yourFragment.isVisible()

First of all isVisible() already checks for isAdded() so no need for calling both. Second, non-of these two means that user is actually seeing your fragment. Only isResumed() makes sure that your fragment is in front of the user and user can interact with it if thats whats you are looking for.


Both isVisible() and isAdded() return true as soon as the Fragment is created, and not even actually visible. The only solution that actually works is:

if (isAdded() && isVisible() && getUserVisibleHint()) {
    // ... do your thing
}

This does the job. Period.

NOTICE: getUserVisibleHint() is now deprecated. be careful.


You should be able to do the following:

MyFragmentClass test = (MyFragmentClass) getSupportFragmentManager().findFragmentByTag("testID");
if (test != null && test.isVisible()) {
     //DO STUFF
}
else {
    //Whatever
}