android官方文档: Helper for tracking the velocity of touch events, for implementing flinging and other such gestures.
用来追踪点击事件的速度,包滑动以及其它手势。 简单的说就是可以用来检测手指在屏幕中滑动的速度。
用法:
obtain();
创建并返回一个VelocityTracker实例,不要忘记最后要调用recyle()方法,让这个对象可以重用。
addMovement (MotionEvent event)
把用户的一个点击事件添加到追踪器中。
computeCurrentVelocity (int units)
computeCurrentVelocity (int units, float maxVelocity)
这2个方法是计算速度,得到的速度为在传入的时间段的速度;第一个方法传入的参数表示时间段;第二个方法的第二个参数表示最大的速度,如果计算得到的速度大于该速度,最后规定的值为这个参数值。如果units为1000ms,表示在1000ms中滑动了多少个像素点。如果units为1ms,表示在1ms中滑动了多少个像素点。 也就是说我们得到的速度都是相对于这个值来说的。
getXVelocity ()
getXVelocity (int id)
获得x轴方向的速度。第一个方法得到最后一次计算的x轴速度,第二个方法表示具体触摸点id的x轴速度。
getYVelocity ()
getYVelocity (int id)
和上上面的类似。 在调用以上4个方法前,必须先要计算速度,也就是先要调用computeCurrentVelocity方法。
clear()
重置速度追踪器到初始状态。
recycle ()
回收内存。
Demo
public class myTestView extends View {
private static final String VELOCITY = "velocity";
private Context mContext;
private int mPointId;
private VelocityTracker mVelocityTracker;
//代码中创建该view
public myTestView(Context context) {
this(context, null);
mContext = context;
}
//从xml文件中创建view需要添加该构造函数,xml中创建会受到一个AttributeSet实例
public myTestView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(null == mVelocityTracker) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//获取点击时第一个触碰点
mPointId = event.getDeviceId();
break;
case MotionEvent.ACTION_UP:
if(mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null; //赋为null
}
break;
case MotionEvent.ACTION_MOVE:
mVelocityTracker.computeCurrentVelocity(1000);
mVelocityTracker.getXVelocity();
mVelocityTracker.getYVelocity();
Log.i(VELOCITY, "XVelocity " + mVelocityTracker.getXVelocity());
Log.i(VELOCITY, "YVelocity " + mVelocityTracker.getYVelocity());
break;
}
return true;
}
}