【发布时间】:2020-05-19 09:13:58
【问题描述】:
我对 java 编程比较陌生,目前在 Android Studio 中遇到了我的 ScrollView 的问题。我希望 scrollView 在用户停止滚动后滚动到视图的开头或结尾,具体取决于滚动停止的位置。我一直在尝试结合 setOnScrollChangeListener() 和 setOnTouchListener() 来检测滚动何时停止。这不起作用,因为一旦启动触摸,滚动将不起作用。
我应该如何解决这个问题?还是我应该使用其他一些视图来代替我的情况更可取?
我在这里找到了一个类似问题的旧答案:Android: Detect when ScrollView stops scrolling by Aleksandarf,其中使用了一个类。但我不明白如何或何时调用课程。
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;
}
}
提前致谢!
【问题讨论】:
标签: java android scrollview onscrolllistener