velocity [və'lɒsəti] n.速度;迅速;速率 ; Tracker 英['trækə] n. 追踪者;跟踪装置 VelocityTracker顾名思义即速度跟踪。
android.view.VelocityTracke主要用跟踪触摸屏事件的速率。在android中主要应用于touch even。 VelocityTracker通过跟踪一连串事件实时计算出当前的速度,比如Gestures中的Fling, Scrolling和其他gestures手势事件等。
使用过程:
- 当你需要跟踪触摸屏事件的速度的时候,使用VelocityTracker.obtain()方法来获得VelocityTracker类的一个实例对象。
- 在onTouchEvent回调函数中,使用addMovement(MotionEvent)函数将当前的移动事件传递给VelocityTracker对象。
- 使用computeCurrentVelocity (int units)函数来初始化速率的单位(获取速率前一定要调用此方法),使用 getXVelocity ()、 getYVelocity ()函数获得横向和竖向的速率到速率。
- 回收VelocityTracker对象
示例代码
private VelocityTracker mVelocityTracker;
linearLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//创建VelocityTracker对象,并将触摸content界面的滑动事件加入到VelocityTracker当中。
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(event);
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
//设置移动速度单位为:像素/10000ms,即1000毫秒内移动的像素
mVelocityTracker.computeCurrentVelocity(1000);
//获取手指在界面滑动的速度。
int velocity = (int) mVelocityTracker.getXVelocity();
textView.setText(velocity+"");
break;
case MotionEvent.ACTION_UP:
//回收对象
mVelocityTracker.recycle();
mVelocityTracker = null;
break;
}
return true;
}
});