Hulk
Hulk

Reputation: 213

Detect if view is scrolled out of the screen

I have layout with scrollView as below :

<ScrollView
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

              <LinearLayout
                    android:id="@+id/transparentLayout"
                    android:layout_width="match_parent"
                    android:layout_height="150dp"
                    android:background="@android:color/transparent"
                    android:orientation="vertical" >
              </LinearLayout>

              ... other views

</ScrollView>

I want to detect if the transparentLayout (LinearLayout) is scrolled out of the screen.

Upvotes: 7

Views: 3693

Answers (1)

Hulk
Hulk

Reputation: 213

I solved it in this fashion:

scrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {

            @Override
            public void onScrollChanged() {

                Rect scrollBounds = new Rect();
                scrollView.getHitRect(scrollBounds);
                if (layout.getLocalVisibleRect(scrollBounds)) {
                    // if layout even a single pixel, is within the visible area do something

                } else {
                    // if layout goes out or scrolled out of the visible area do something

                }

            }
        });

Upvotes: 13

Related Questions