Android: How to determine if a view is onscreen, offscreen or partially offScreen/partially visible?

D C
1 min readFeb 20, 2021

--

I have come across this question a plenty number of time. The solution is quiet simple:

For a given view v, one can determine the Global Visible Rectangle of the view v by:

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

In the above code snippet globalVisibilityRectangle variable will be populated with coordinates of the view which are only visible on screen. From the globalVisibilityRectangle variable we can extract visible height and visible width of the view, like this:

int visibleHeight = globalVisibilityRectangle.right - globalVisibilityRectangle.left;int visibleWidth = globalVisibilityRectangle.bottom - globalVisibilityRectangle.top;

Now is the part where we want to grab the actual height and actual width of the view v:

int actualHeight = v.getMeasuredHeight();
int actualWidth = v.getMeasuredWidth();

If the view is onScreen(not even overshadowed by any other view) then the below statement will be true:

visibleHeight == actualHeight

If the view is partiallyVisible (partially over shadowed by another view or partially off screen) then the below statement will be true:

visibleHeight < actualHeight && visibleHeight > 0

If the view is totally offScreen(not even a small part visible) then the below statement will be true:

visibleHeight < actualHeight && visibleHeight <= 0

I hope, it helps.

--

--

Responses (3)