在进入手势操作前,先来看看一些处理触摸时遗漏了的要点--VelocityTracker。顾名思义,VelocityTracker就是速度跟踪的意思。我们可以获得触摸点的坐标,根据按下的时间可以简单的计算出速度的大小。但是这样会令我们的代码混乱。Android直接提供了一种方式来方便我们获得触摸的速度。
- publicclassVelocityTrackerActivityActivityextendsActivity{
- /**Calledwhentheactivityisfirstcreated.*/
- TextViewtextView;
- privateVelocityTrackervTracker=null;
- @Override
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- textView=(TextView)findViewById(R.id.textView);
- }
- @Override
- publicbooleanonTouchEvent(MotionEventevent){
- intaction=event.getAction();
- switch(action){
- caseMotionEvent.ACTION_DOWN:
- if(vTracker==null){
- vTracker=VelocityTracker.obtain();
- }else{
- vTracker.clear();
- }
- vTracker.addMovement(event);
- break;
- caseMotionEvent.ACTION_MOVE:
- vTracker.addMovement(event);
- vTracker.computeCurrentVelocity(1000);
- textView.setText("thexvelocityis"+vTracker.getXVelocity());
- textView.append("theyvelocityis"+vTracker.getYVelocity());
- break;
- caseMotionEvent.ACTION_UP:
- caseMotionEvent.ACTION_CANCEL:
- vTracker.recycle();
- break;
- }
- event.recycle();
- returntrue;
- }
- }
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)。