/ 0评 / 1

# 速度追踪--VelocityTracker

### 方法摘要

public static VelocityTracker obtain()

Retrieve a new VelocityTracker object to watch the velocity of a motion. Be sure to call recycle() when done. You should generally only maintain an active object while tracking a movement, so that the VelocityTracker can be re-used elsewhere.

public void recycle()

Return a VelocityTracker object back to be re-used by others. You must not touch the object after calling this function.

public void clear()

Reset the velocity tracker back to its initial state.

Add a user's movement to the tracker. You should call this for the initial MotionEvent.ACTION_DOWN, the following MotionEvent.ACTION_MOVE events that you receive, and the final MotionEvent.ACTION_UP. You can, however, call this for whichever events you desire.

public void computeCurrentVelocity(int units)

Compute the current velocity based on the points that have been collected. Only call this when you actually want to retrieve velocity information, as it is relatively expensive. You can then retrieve the velocity with getXVelocity() and getYVelocity().

public float getXVelocity()

Retrieve the last computed X velocity. You must first call computeCurrentVelocity(int) before calling this function.

public float getYVelocity()

Retrieve the last computed Y velocity. You must first callcomputeCurrentVelocity(int) before calling this function.

### 使用过程

VelocityTracker主要用来追踪手指在滑动过程中的速度，包括水平速度和竖直方向的速度，它的使用过程很简单，首先在View的onTouchEvent方法中追踪当前单击事件的速度

VelocityTracker mVelocityTracker =  VelocityTracker.obtain();

mVelocityTracker.computeCurrentVelocity(1000);

float xVelocity = mVelocityTracker.getXVelocity();

float yVelocity = mVelocityTracker.getYVelocity();

mVelocityTracker.clear();

mVelocityTracker.recycle();

### 回收时机

View中两个回调函数：

/**
* This is called when the view is attached to a window. At this point it
* has a Surface and will start drawing. Note that this function is
* guaranteed to be called before onDraw(android.graphics.Canvas), however
* it may be called any time before the first onDraw -- including before or
* after onMeasure(int, int).
*/
@Override
protected void onAttachedToWindow() {
// TODO Auto-generated method stub
super.onAttachedToWindow();
}

/**
* This is called when the view is detached from a window. At this point it
* no longer has a surface for drawing.
*/
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
}
• 默认
• 护眼
• 夜晚
• Serif
• Sans