Scrollview: check if a view is visible on screen or not
Asked Answered
S

4

20

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)?

Shem answered 23/4, 2014 at 13:57 Comment(3)
Check out this answer: https://mcmap.net/q/125585/-how-can-i-check-if-a-view-is-visible-or-not-in-android-duplicateWrightson
This post might help: [#4629300 [1]: #4629300Usury
Check this answer #4629300Bharal
B
33

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
}
Busywork answered 8/9, 2016 at 13:24 Comment(1)
I could find a case to have view.getGlobalVisibleRect(rect) return true :(Frogfish
H
11

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
}
Headstrong answered 1/11, 2017 at 21:37 Comment(0)
I
3

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

Iterate answered 13/8, 2021 at 11:48 Comment(0)
N
0

I wrote Kotlin extension function for that:

fun View.isViewFullyVisible(): Boolean {
    val localVisibleRect = Rect()
    getLocalVisibleRect(localVisibleRect)
    return localVisibleRect.top == 0 && localVisibleRect.bottom == height
}
Nary answered 28/3 at 11:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.