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;
}
});