ab11 ab11 - 1 year ago 176
Android Question

Android: how to check if a View inside of ScrollView is visible?

I have a

which holds a series of
. I would like to be able to determine if a view is currently visible (if any part of it is currently displayed by the
). I would expect the below code to do this, surprisingly it does not:

Rect bounds = new Rect();

Rect scrollBounds = new Rect(scroll.getScrollX(), scroll.getScrollY(),
scroll.getScrollX() + scroll.getWidth(), scroll.getScrollY() + scroll.getHeight());

if(Rect.intersects(scrollBounds, bounds))
//is visible

Answer Source

Use View#getHitRect instead of View#getDrawingRect on the view you're testing. You can use View#getDrawingRect on the ScrollView instead of calculating explicitly.

Code from View#getDrawingRect:

 public void getDrawingRect(Rect outRect) {
        outRect.left = mScrollX;
        outRect.top = mScrollY;
        outRect.right = mScrollX + (mRight - mLeft);
        outRect.bottom = mScrollY + (mBottom - mTop);

Code from View#getHitRect:

public void getHitRect(Rect outRect) {
        outRect.set(mLeft, mTop, mRight, mBottom);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download