VelocityTracker使用demo
/**
* 速率追踪类的使用demo:
* 1、实例化,在需要的地方通过obtain方法获取
* 2、在ontouch时间把event设置给追踪类,并设置computeCurrentVelocity,一般是给1000,这里也可以设置
* 3、在down动作下捕捉触点id,然后在move动作就可以计算实时的速率了
* 4、可以在cancel或者up进行追踪类的释放(有误):在这里释放再次再次滑动就会报我的追踪类空了,所以我们在activity的destroy的时候去释放
*/
public class MainActivity extends Activity {
private VelocityTracker mVelocityTracker;
private int id;
private TextView mInfo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mInfo = new TextView(this);
mInfo.setLines(4);
mInfo.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
mInfo.setTextColor(Color.BLACK);
setContentView(mInfo);
mVelocityTracker = VelocityTracker.obtain();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mVelocityTracker.addMovement(event);
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
//获取触点的ID,因为可能有多个。0代表第一个
id = event.getPointerId(0);
break;
case MotionEvent.ACTION_MOVE:
mVelocityTracker.computeCurrentVelocity(1000);
float vX = mVelocityTracker.getXVelocity(id);
float vY = mVelocityTracker.getYVelocity(id);
mInfo.setText("顺时速度x " + vX + "顺时速度y " + vY);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
//releaseVelocityTracker();
break;
}
return super.onTouchEvent(event);
}
//释放VelocityTracker
private void releaseVelocityTracker() {
if (null != mVelocityTracker) {
mVelocityTracker.clear();
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
}