I'm rather new to java programming and is curently facing a problem with my ScrollView in Android Studio. I would like for the scrollView to either scroll to the beggining or the end of the view after the user has stopped scrolling, depending on where the scrolling is stopped. I've been trying out the setOnScrollChangeListener() combined with the setOnTouchListener() to detect when the scrolling has been stopped. This doesn't work because once the touch is initiated the scrolling won't function.
How should I tackle this problem? Or is there some other view I should use instead which would be more preferable in my case?
I found an old answer to a similar problem here: Android: Detect when ScrollView stops scrolling by Aleksandarf where a class is being used. But I don't understand how or when to call the class.
public class ScrollViewWithOnStopListener extends ScrollView {
OnScrollStopListener listener;
public interface OnScrollStopListener {
void onScrollStopped(int y);
}
public ScrollViewWithOnStopListener(Context context) {
super(context);
}
public ScrollViewWithOnStopListener(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_UP:
checkIfScrollStopped();
}
return super.onTouchEvent(ev);
}
int initialY = 0;
private void checkIfScrollStopped() {
initialY = getScrollY();
this.postDelayed(new Runnable() {
@Override
public void run() {
int updatedY = getScrollY();
if (updatedY == initialY) {
//we've stopped
if (listener != null) {
listener.onScrollStopped(getScrollY());
}
} else {
initialY = updatedY;
checkIfScrollStopped();
}
}
}, 50);
}
public void setOnScrollStoppedListener(OnScrollStopListener yListener) {
listener = yListener;
}
}
Thanks in advance!