How can you tell if a View is visible on screen in Android?

user1847544 picture user1847544 · Dec 26, 2012 · Viewed 44k times · Source

I want to check if a View within a ScrollView is currently visible in Android. I am not checking if it is focused on yet but if it is currently being displayed on screen. Is there a method in View that can tell me if the view is currently visible?

Answer

zegee29 picture zegee29 · Feb 28, 2018

This code works for me:

public static boolean isVisible(final View view) {
    if (view == null) {
        return false;
    }
    if (!view.isShown()) {
        return false;
    }
    final Rect actualPosition = new Rect();
    view.getGlobalVisibleRect(actualPosition);
    final Rect screen = new Rect(0, 0, getScreenWidth(), getScreenHeight());
    return actualPosition.intersect(screen);
}