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

后端 未结 5 816
你的背包
你的背包 2020-12-23 19:32

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 bei

5条回答
  •  借酒劲吻你
    2020-12-23 20:03

    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.

提交回复
热议问题