VelocityTracker的介绍:
简单来说就是:X/Y方向的速度相关的帮助类
/**
* Helper for tracking the velocity of touch events, for implementing flinging and other such gestures.
* Use obtain to retrieve a new instance of the class when you are going to begin tracking.
* Put the motion events you receive into it with addMovement(MotionEvent).
* When you want to determine the velocity call computeCurrentVelocity(int) and then call getXVelocity(int) and getYVelocity(int) to retrieve the velocity for each pointer id.
*/
使用步骤:
-
声明
private VelocityTracker mVelocityTracker;
-
初始化
private void init() { mVelocityTracker = VelocityTracker.obtain(); }
-
在onTouchEvent的开头添加滑动事件
public boolean onTouchEvent(MotionEvent event) { mVelocityTracker.addMovement(event); ... }
-
在onTouchEvent的MotionEvent.ACTION_UP中使用
case MotionEvent.ACTION_UP: { int scrollX = getScrollX(); int scrollToChildIndex = scrollX / mChildWidth; mVelocityTracker.computeCurrentVelocity(1000); float xVelocity = mVelocityTracker.getXVelocity(); if (Math.abs(xVelocity) >= 50) { mChildIndex = xVelocity > 0 ? mChildIndex - 1 : mChildIndex + 1; } else { mChildIndex = (scrollX + mChildWidth / 2) / mChildWidth; } mChildIndex = Math.max(0, Math.min(mChildIndex, mChildrenSize - 1)); int dx = mChildIndex * mChildWidth - scrollX; smoothScrollBy(dx, 0); mVelocityTracker.clear(); break; }
-
在onDetachedFromWindow中回收
@Override protected void onDetachedFromWindow() { mVelocityTracker.recycle(); super.onDetachedFromWindow(); }