Search code examples
androidfragment

How to check if the fragment is visible to user


How to check if a fragment is visible to the user in an Android app?

I have an app where the Home activity has several fragments. One of the fragments listens to events from another activity started from Home and hence executing a method every time I come back to Home from that activity. While what I want is to only trigger those events and have the method executed if the fragment is visible to the user in the foreground.

I have tried the following but nothing seemed to work:

  1. isAdded() and isVisible() check - always return true as soon as the fragment the created, irrespective of fragment actually visible to the user or not.
  2. getUserVisibleHint() - this again would return true even if I was still in the other activity. Additionally, it is deprecated as well, so even if it worked I would want to look for another solution.

I have come to a dead-end to find an actual working way to check if the fragment is actually visible to the user and not just added to memory.

Any help on this is appreciated!


Solution

  • I finally came across the solution while trying myself:

    Simple check for isResumed() and it'd only return true if the fragment is in the foreground and resumed state.

    Just to be safe, check for isVisible which also checks for isAdded internally and would reduce the condition, so a simple if-condition:

    if (isVisible() && isResumed()) {
        // perform your action here
    }
    

    This worked for me!