利用VelocityTracker监控对触摸的速度跟踪
VelocityTracker就是速度跟踪的意思。我们可以获得触摸点的坐标,根据按下的时间可以简单的计算出速度的大小。
Android直接提供了一种方式来方便我们获得触摸的速度。
public class VelocityTrackerActivityActivity extends Activity {
/** Called when the activity is first created. */
TextView textView;
private VelocityTracker vTracker = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textView = (TextView)findViewById(R.id.textView);
}
@Override
public boolean onTouchEvent(MotionEvent event){
int action = event.getAction();
switch(action){
case MotionEvent.ACTION_DOWN:
if(vTracker == null){
vTracker = VelocityTracker.obtain();
}else{
vTracker.clear();
}
vTracker.addMovement(event);
break;
case MotionEvent.ACTION_MOVE:
vTracker.addMovement(event);
vTracker.computeCurrentVelocity(1000);
textView.setText("the x velocity is "+vTracker.getXVelocity());
textView.append("the y velocity is "+vTracker.getYVelocity());
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
vTracker.recycle();
break;
}
event.recycle();
return true;
}
}
VelocityTracker不仅可以处理单点的速度,也可以获得多点的速度。这和处理多点触摸的方式是一样的,传入一个ID就可以了。VelocityTracker获得的速度是有正负之分,computerCurrentVelocity()可以设置单位。1000 表示每秒多少像素(pix/second),1代表每微秒多少像素(pix/millisecond)。