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

M. Usman Khan
  • 3,689
  • 1
  • 59
  • 69
giozh
  • 9,868
  • 30
  • 102
  • 183
  • 2
    Check out this answer: [http://stackoverflow.com/a/12428208/798634](http://stackoverflow.com/a/12428208/798634) – Matt K Apr 23 '14 at 14:01
  • This post might help: [http://stackoverflow.com/questions/4628800/android-how-to-check-if-a-view-inside-of-scrollview-is-visible][1] [1]: http://stackoverflow.com/questions/4628800/android-how-to-check-if-a-view-inside-of-scrollview-is-visible – Steve Waring Aug 27 '14 at 07:58
  • Check this answer https://stackoverflow.com/questions/4628800/android-how-to-check-if-a-view-inside-of-scrollview-is-visible/47280300#47280300 – Himanshu Nov 14 '17 at 09:15

3 Answers3

31

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
}
gio
  • 4,950
  • 3
  • 32
  • 46
Akash Dubey
  • 327
  • 4
  • 5
9

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
}
Chad Bingham
  • 32,650
  • 19
  • 86
  • 115
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