您的位置:首页 > 移动开发 > Android开发

VelocityTracker的用法

2016-03-11 11:16 525 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Android velocity