Reputation: 10068
I have a ScrollView defined like:
<ScrollView
...
.../>
<LinearLayout
...
...>
<!-- content -->
</LinearLayout>
</ScrollView>
And I fill the LinearLayout dynamically with some ImageViews. Now, is there a way to check when an ImageView gets visible or invisible (for example when i scroll down)?
Upvotes: 20
Views: 25625
Reputation: 764
I wrote Kotlin extension function for that:
fun View.isViewFullyVisible(): Boolean {
val localVisibleRect = Rect()
getLocalVisibleRect(localVisibleRect)
return localVisibleRect.top == 0 && localVisibleRect.bottom == height
}
Upvotes: 1
Reputation: 31
I struggled a lot to get an accurate answer and th following solved my problem
final ScrollView scrollView = findViewById(R.id.scrollView);
scrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (yourImageView.getLocalVisibleRect(scrollBounds)) {
// The ImageView is Visible on the screen while scrolling
} else {
// The ImageView is not Visible on the screen while scrolling
}
}
});
The code within the OnScrollChangedListener keeps checking if the Imageview is visible and shown on the screen and once you scroll and the imageview is not visible it gets detected immediately
Upvotes: 3
Reputation: 33876
I will forward you to this answer:
If the image is part of the layout it might be "View.VISIBLE" but that doesn't mean it's within the confines of the visible screen. If that's what you're after; this will work:
Rect scrollBounds = new Rect();
scrollView.getHitRect(scrollBounds);
if (imageView.getLocalVisibleRect(scrollBounds)) {
// imageView is within the visible window
} else {
// imageView is not within the visible window
}
Upvotes: 11
Reputation: 347
To check if the view is fully/partially visible you can use :
boolean isViewVisible = view.isShown();
To determine if it is fully visible use below approach:
Rect rect = new Rect();
if(view.getGlobalVisibleRect(rect)
&& view.getHeight() == rect.height()
&& view.getWidth() == rect.width() ) {
// view is fully visible on screen
}
Upvotes: 33