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

安卓VelocityTracker使用小例子

2016-07-21 14:59 513 查看

安卓VelocityTracker使用小例子

定义:

VelocityTracker是位于android.view.VelocityTracker的一个工具类,用于监听滑动的速度,顾名思义Velocity(速度)Tracker(追踪者)


常用api

/**
* Retrieve a new VelocityTracker object to watch the velocity of a
* motion.  Be sure to call {@link #recycle} when done.  You should
* generally only maintain an active object while tracking a movement,
* so that the VelocityTracker can be re-used elsewhere.
*
* @return Returns a new VelocityTracker.
*/
static public VelocityTracker obtain() {
VelocityTracker instance = sPool.acquire();
return (instance != null) ? instance : new VelocityTracker(null);
}


获取一个实例 VelocityTracker v= VelocityTracker.obtain();

已经获得初始化的VelocityTracker实例,那么就要和事件中的android.view.MotionEvent做关联,调用如下函数

/**
* Add a user's movement to the tracker.  You should call this for the
* initial {@link MotionEvent#ACTION_DOWN}, the following
* {@link MotionEvent#ACTION_MOVE} events that you receive, and the
* final {@link MotionEvent#ACTION_UP}.  You can, however, call this
* for whichever events you desire.
*
* @param event The MotionEvent you received and would like to track.
*/
public void addMovement(MotionEvent event) {
if (event == null) {
throw new IllegalArgumentException("event must not be null");
}
nativeAddMovement(mPtr, event);
}


关联完毕后,就应该获取了,这个时候就可以先设置使用

public void computeCurrentVelocity(int units) ;

int 参数指的就是监测时间

/**
* Equivalent to invoking {@link #computeCurrentVelocity(int, float)} with a maximum
* velocity of Float.MAX_VALUE.
*
* @see #computeCurrentVelocity(int, float)
*/
public void computeCurrentVelocity(int units) {
nativeComputeCurrentVelocity(mPtr, units, Float.MAX_VALUE);
}


所有的准备工作都可以了,然后就能调用

getXVelocity(),getYVelocity()来获取速度了

函数原型,其他同理

/**
* Retrieve the last computed X velocity.  You must first call
* {@link #computeCurrentVelocity(int)} before calling this function.
*
* @return The previously computed X velocity.
*/
public float getXVelocity() {
return nativeGetXVelocity(mPtr, ACTIVE_POINTER_ID);
}


最后一步就是记得回收,调用recycle()

* Return a VelocityTracker object back to be re-used by others.  You must
* not touch the object after calling this function.
*/
public void recycle() {
if (mStrategy == null) {
clear();
sPool.release(this);
}
}


简单示例:

VelocityTracker mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(/*要监听的MotionEvent*/);
mVelocityTracker.computeCurrentVelocity(1000);//设置时间
mVelocityTracker.getXVelocity());//获取x轴1000毫秒单位速度
mVelocityTracker.recycle();
//使用完毕回收资源,比如一个onTouch事件中开始是obtain获取实例
//,那么,在onTouch事件结束的时候就需要回收(recycle())
mVelocityTracker = null;


注意事项:

有时候如果没有通过obtain()获取就使用的话,会导致错误

必须先调用computeCurrentVelocity(毫秒时间),才能用get系列方法来
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  velocity android