I have a fixed content in my text view inside a scroll view. When the user scrolls to a certain position, I would like to start an activity or trigger a Toast
.
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:id="@+id/scroller">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent" android:id="@+id/story"
android:layout_height="wrap_content" android:text="@string/lorem"
android:gravity="fill" />
</LinearLayout>
</ScrollView>
My problem is in implementing the protected method onScrollChanged
to find out the position of the scroll view.
I have found this answer, is there an easier solution to this rather than declaring an interface, over ride the scrollview etc as seen on the link I posted?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With