Android - 滚动停止后如何滚动到滚动视图的开始或结束?



我对Java编程相当陌生,并且在Android Studio中的ScrollView中遇到了一个问题。我希望scrollView在用户停止滚动后滚动到视图的开头或结尾,具体取决于停止滚动的位置。我一直在尝试将setOnScrollChangeListener((与setOnTouchListener((结合使用,以检测滚动何时停止。这不起作用,因为一旦启动触摸,滚动将不起作用。

我应该如何解决这个问题?或者我应该使用其他一些视图,这在我的情况下更可取?

我在这里找到了类似问题的旧答案:Android:检测ScrollView何时停止滚动,由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;
}
} 

提前感谢!

嗨,我使用您在此处提供的链接和另一个问题(Android:如何在顶部滚动滚动视图。

创建一个名为CustomScrollView的类:

public class CustomScrollView extends ScrollView {
private long lastScrollUpdate = -1;
public CustomScrollView(Context context) { super(context);}
public CustomScrollView(Context context, AttributeSet attrs) { super(context,attrs);}
public CustomScrollView (Context context, AttributeSet attrs, int default_style){super(context, attrs, default_style);}
private class ScrollStateHandler implements Runnable {
@Override
public void run() {
long currentTime = System.currentTimeMillis();
if ((currentTime - lastScrollUpdate) > 100) {
lastScrollUpdate = -1;
onScrollEnd();
} else {
postDelayed(this, 100);
}
}
}
@Override
protected void onScrollChanged(int l, int t, int oldl, int oldt) {
super.onScrollChanged(l, t, oldl, oldt);
if (lastScrollUpdate == -1) {
onScrollStart();
postDelayed(new ScrollStateHandler(), 100);
}
lastScrollUpdate = System.currentTimeMillis();
}
private void onScrollStart() {
// Feel Free to add something here
}
private void onScrollEnd() {
this.fullScroll(View.FOCUS_UP); // Each time user finish with scrolling it will scroll to top
}}

在 XML 中添加:

<YOUR-PACKAGE-NAME.CustomScrollView
android:id="@+id/scrollMe"
android:layout_width="match_parent"
android:layout_height="100dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="tESTnSCROLL DOWNnnnnHello World!n test n test nSCROLLn"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</YOUR-PACKAGE-NAME.CustomScrollView>

随意问任何:)

最新更新