/**
* 计算滑动速率
*
*/
public class VelocityTrackerDemoActivity extends Activity {
private static final String INFO = "手指在屏幕上滑动";
private int mMaximumVelocity;
private VelocityTracker mVelocityTracker;
private TextView mTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTextView = (TextView) findViewById(R.id.textView);
mTextView.setText(INFO);
final ViewConfiguration configuration = ViewConfiguration.get(this);
mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int action = event.getAction();
if (mVelocityTracker == null) {
// 获得VelocityTracker类的一个实例对象
mVelocityTracker = VelocityTracker.obtain();
}
// 添加跟踪
// 将当前的移动事件传递给VelocityTracker对象
mVelocityTracker.addMovement(event);
switch (action) {
case MotionEvent.ACTION_MOVE:
// mTracker.addMovement(event);
// 计算当前的速度
// 1000,初始化速率的单位 表示每秒多少像素(pix/second),1代表每微秒多少像素(pix/millisecond)。
final VelocityTracker velocityTracker = mVelocityTracker;
velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
mTextView.setText(INFO + " \n横向速率是 : "+mVelocityTracker.getXVelocity());
mTextView.append("\n 纵向速率是: "+mVelocityTracker.getYVelocity());
break;
case MotionEvent.ACTION_CANCEL:
// 这里可以获取滑动的速率
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
break;
}
return true;
}
}