I have a ScrollView
which holds a series of Views
. I would like to be able to determine if a view is currently visible (if any part of it is currently displayed by the ScrollView
). I would expect the below code to do this, surprisingly it does not:
Rect bounds = new Rect();
view.getDrawingRect(bounds);
Rect scrollBounds = new Rect(scroll.getScrollX(), scroll.getScrollY(),
scroll.getScrollX() + scroll.getWidth(), scroll.getScrollY() + scroll.getHeight());
if(Rect.intersects(scrollBounds, bounds))
{
//is visible
}
I you want to detect if your
View
is fullyvisible
, try with this method:Strictly speaking you can get the visibility of a view with:
The posible constant values of the visibility in a View are:
VISIBLE This view is visible. Use with setVisibility(int) and android:visibility.
INVISIBLE This view is invisible, but it still takes up space for layout purposes. Use with setVisibility(int) and android:visibility.
GONE This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility.
You can use the
FocusAwareScrollView
which notifies when view becomes visible :Here is class :
If you want to detect that the view is FULLY visible:
I faced the same problem today. While Googling and reading Android reference I found this post and a method I ended up using instead;
Nice of them not to only providing Rect but also boolean indicating if View visible at all. On negative side this method is undocumented :(
This works:
To expand a bit on Bill Mote's answer using getLocalVisibleRect, you may want to check if the view is only partially visible: