Android scrollview onScrollChanged

There is a much easier way than subclassing the ScrollView. The ViewTreeObserver object of the ScrollView can be used to listen for scrolls.

Since the ViewTreeObserver object might change during the lifetime of the ScrollView, we need to register an OnTouchListener on the ScrollView to get it's ViewTreeObserver at the time of scroll.

final ViewTreeObserver.OnScrollChangedListener onScrollChangedListener = new
                           ViewTreeObserver.OnScrollChangedListener() {

    @Override
    public void onScrollChanged() {
        //do stuff here 
    }
};

final ScrollView scrollView = (ScrollView) findViewById(R.id.scroller);
scrollView.setOnTouchListener(new View.OnTouchListener() {
    private ViewTreeObserver observer;

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (observer == null) {
            observer = scrollView.getViewTreeObserver();
            observer.addOnScrollChangedListener(onScrollChangedListener);
        }
        else if (!observer.isAlive()) {
            observer.removeOnScrollChangedListener(onScrollChangedListener);
            observer = scrollView.getViewTreeObserver();
            observer.addOnScrollChangedListener(onScrollChangedListener);
        }

        return false;
    }
});

No.

ScrollView doesn't provide a listener for scroll events or even a way to check how far down the user has scrolled, so you have to do what is suggested by the link.


This question is fairly old, but in case somebody drops by (like me):

Starting with API 23, Android's View has a OnScrollChangeListener and the matching setter.

The NestedScrollView from the Support library also supports setting a scroll listener even before that API level. As far as I know, NestedScrollView can be used as a replacement for the normal ScrollView without any problems.