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

2019-02-03 02:20发布

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?

5条回答
Root(大扎)
2楼-- · 2019-02-03 02:42

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);
}
查看更多
啃猪蹄的小仙女
3楼-- · 2019-02-03 02:43

The getVisibility() method will help you to check the visibility of any View.

Example:

if(view.getVisibility() == View.VISIBLE) {
    // Visible
} else { 
    // Invisible
}
查看更多
趁早两清
4楼-- · 2019-02-03 02:49
int[] location = new int[2];
view.getLocationOnScreen(location);

or

Rect rect = new Rect();
view.getGlobalVisibleRect(rect);

Now use this location or rectangle to check if it is in your visible bounds or not. If it is simply the entire screen, check against getResources().getDisplayMetrics().

As pointed by Antek in the comments below, the view may still be gone or invisible with the returned values here telling where it was last drawn. So combining the above bounds-related condition with an view.isShown() or view.getVisibility() == VISIBLE should take care of that.

查看更多
乱世女痞
5楼-- · 2019-02-03 03:06

The function View.getVisibility() can have below values:

  • View.VISIBLE (0): the view is visible.

  • View.INVISIBLE (1): The view is invisible, but it still takes up space for layout purposes.

  • View.GONE (2): the view is gone. Completely hidden, as if the view had not been added

You can see below link for more info. How can I check if a view is visible or not in Android?

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-02-03 03:09

try

if(view.isShown()) {
    // Visible
} else { 
    // Invisible
}
查看更多
登录 后发表回答