【参考链接】
可以使用VelocityTracker类来获得手指滑动时的速度
假设computeCurrentVelocity()中设置的时间间隔是1000ms,在1000ms内手指在水平方向从左向右滑动了100像素,那么计算出来的值就是100。
注意速度的正负值跟屏幕坐标系方向保持一致。
@Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(event);
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.e("shadowfaxghh", "ACTION_DOWN");
lastX=(int) event.getRawX();
obtaionVelocityTracker();
mVelocityTracker.addMovement(event);
break;
case MotionEvent.ACTION_MOVE:
Log.e("shadowfaxghh", "ACTION_MOVE");
int newX= (int) event.getRawX();
int deltaX=newX-lastX;
// if (Math.abs(deltaX) >ViewConfiguration.get(getContext()).getScaledTouchSlop()) {
int newScrollX = getScrollX() + (-deltaX);
if (newScrollX > maxScrollX)
newScrollX = maxScrollX;
if (newScrollX < minScrollX)
newScrollX = minScrollX;
scrollTo(newScrollX, getScrollY());
//更新坐标
lastX = newX;
// }
obtaionVelocityTracker();
mVelocityTracker.addMovement(event);
break;
case MotionEvent.ACTION_UP:
Log.e("shadowfaxghh", "ACTION_UP");
lastX=(int) event.getRawX();
if(mVelocityTracker!=null) {
//计算速度
mVelocityTracker.computeCurrentVelocity(1000, scaledMaximumFlingVelocity);
//获取x方向的速度
int xVelocity = (int) mVelocityTracker.getXVelocity();
Log.e("shadowfaxghh", "xVelocity=" + xVelocity);
recycleVelocityTracker();
}
break;
case MotionEvent.ACTION_CANCEL:
Log.e("shadowfaxghh", "ACTION_CANCEL");
lastX=(int) event.getRawX();
recycleVelocityTracker();
break;
default:
break;
}
return true;
}
private void obtaionVelocityTracker(){
if(mVelocityTracker==null)
mVelocityTracker=VelocityTracker.obtain();
}
private void recycleVelocityTracker(){
if(mVelocityTracker!=null){
mVelocityTracker.clear();
mVelocityTracker.recycle();
mVelocityTracker=null;
}
}