核心代码如下:
private NestedScrollView scrollView;
private int scrollDy = 0;
private int scrollOldDy = 0;
private void scrollAnimate() {
scrollView.setOnScrollChangeListener(new View.OnScrollChangeListener() {
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
scrollDy = scrollY;
scrollOldDy= oldScrollY;
}
});
scrollView.setOnTouchListener(new View.OnTouchListener() {
boolean result = false;
long startTime = 0;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startTime = System.currentTimeMillis();
break;
case MotionEvent.ACTION_MOVE:
result = false;
break;
case MotionEvent.ACTION_UP:
long time = System.currentTimeMillis() - startTime;
Log.i(TAG, "onTouch: 时间:" + time);
if (time == 0) {
// 极快1毫秒
time = 1;
}
// 滑动的距离,正数-向上;负数-向下
int distant = scrollDy - scrollOldDy;
float speed = distant * 1f / time;
if (scrollDy < 150) {
if (speed > 0.5) {
// 速度大于0.5,当做快速滑动,滑动顶部
scrollView.smoothScrollTo(0, 300, 200);
} else {
scrollView.smoothScrollTo(0, 0, 200);
}
} else if (scrollDy < 300) {
if (speed < 0 && Math.abs(speed) > 0.5) {
scrollView.smoothScrollTo(0, 0, 200);
} else {
scrollView.smoothScrollTo(0, 300, 200);
}
}
Log.i(TAG, "onTouch: 起始:" + scrollOldDy);
Log.i(TAG, "onTouch: 结束:" + scrollDy);
Log.i(TAG, "onTouch: 距离:" + distant);
Log.i(TAG, "onTouch: 速度:" + speed);
result = true;
break;
}
return result;
}
});
}