Can I have onScrollListener for a ScrollView?
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
}
});
This might be very useful.
Use NestedScrollView
instead of ScrollView
. Support Library 23.1 introduced an OnScrollChangeListener
to NestedScrollView
.
So you can do something like this.
myScrollView.setOnScrollChangeListener(new NestedScrollView.OnScrollChangeListener() {
@Override
public void onScrollChange(NestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
Log.d("ScrollView","scrollX_"+scrollX+"_scrollY_"+scrollY+"_oldScrollX_"+oldScrollX+"_oldScrollY_"+oldScrollY);
//Do something
}
});