Search code examples
androidlistenerscrollview

Can I have onScrollListener for a ScrollView?


I am using a HorizontalScrollView in a layout and I need to identify the user have reached the start and end point of the scroll.

For ListView I have tried a the onScrollListener and it is possible to find the start and end point of scroll.

I tried to do the same in my Scrollview but it seems not possible. Is there any other possible ways to achieve what I need.


Solution

  • Every instance of View calls getViewTreeObserver(). Now when holding an instance of ViewTreeObserver, you can add an OnScrollChangedListener() to it using the method addOnScrollChangedListener().

    You can see more information about this class here.

    It lets you be aware of every scrolling event - but without the coordinates. You can get them by using getScrollY() or getScrollX() from within the listener though.

    scrollView.getViewTreeObserver().addOnScrollChangedListener(new OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int scrollY = rootScrollView.getScrollY(); // For ScrollView
            int scrollX = rootScrollView.getScrollX(); // For HorizontalScrollView
            // DO SOMETHING WITH THE SCROLL COORDINATES
        }
    });