VelocityTracker在API中解释如下:
Helper for tracking the velocity of touch events, for implementing flinging and other such gestures. Use obtain()
to retrieve a new instance of the class when you are going to begin tracking, put the motion events you receive into it with addMovement(MotionEvent)
, and when you want to determine the velocity call computeCurrentVelocity(int)
and then getXVelocity()
and getYVelocity()
.
方法如下:
简单的Demo(我已经把网上的demo代码竟可能的简化了,这样看起来清晰一些)
package com.example.velocitytrackertest;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
public class MainActivity extends Activity {
private VelocityTracker velocityTracker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//必须放这里,放在ACTION_DOWN里面XY输出为0
if(velocityTracker == null){
velocityTracker = VelocityTracker.obtain();//必须和recycle()配对
}
velocityTracker.addMovement(event);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
velocityTracker.computeCurrentVelocity(1000);
int X = (int)velocityTracker.getXVelocity();
int Y = (int)velocityTracker.getYVelocity();
Log.i("X", X + "");
Log.i("Y", Y + "");
break;
case MotionEvent.ACTION_UP:
if(velocityTracker != null){
velocityTracker.recycle();
velocityTracker = null;
}
break;
}
return super.onTouchEvent(event);
}
}