原文地址:http://android.xsoftlab.net/training/gestures/movement.html
这节课将会学习如何在触摸事件中记录手指移动的轨迹。
当手指触摸的位置、压力或者尺寸发生变化时,ACTION_MOVE事件就会被触发。与Detecting Common Gestures中描述的一样,所有的事件都被记录在一个MotionEvent对象中。
因为基于手指的触摸并不是很精确的交互方式,所以检测触摸事件的行为需要更多的轨迹点。为了帮助APP区分基于轨迹的手势(比如滑动等移动的手势)与非轨迹手势(比如单点等不移动的手势),Android提出了一个名为”touch slop”的概念。Touch slop指的是用户按下的以像素为单位的距离。
这里有若干项不同的追踪手势轨迹的方法,具体使用哪个方法取决于应用程序的需求:
- 指针的起始位置与结束位置。
- 指针位移的方向,由X,Y的坐标判断。
- 历史记录,你可以通过getHistorySize()获得手势的历史尺寸。然后可以通过getHistorical(Value)方法获得这些历史事件的位置,尺寸,事件以及压力。当渲染手指的轨迹时,比如在屏幕上用手指画线条等,历史记录这时就会派上用场。
- 指针在屏幕上滑动的速度。
轨迹的速度
在记录手势的特性或者在检查何种手势事件发生时,除了要依靠手指移动的距离、方向这两个要素之外。还需要另外一个非常重要的因素就是速度。为了使速度计算更加容易,Android为此提供了VelocityTracker类以及VelocityTrackerCompat类。VelocityTracker用于辅助记录触摸事件的速度。这对于判断哪个速度是手势的标准部分,比如飞速滑动。
下面的例子用于演示在VelocityTracker API中方法的目的:
public class MainActivity extends Activity {private static final String DEBUG_TAG = "Velocity";...private VelocityTracker mVelocityTracker = null;@Overridepublic boolean onTouchEvent(MotionEvent event) {int index = event.getActionIndex();int action = event.getActionMasked();int pointerId = event.getPointerId(index);switch(action) {case MotionEvent.ACTION_DOWN:if(mVelocityTracker == null) {// Retrieve a new VelocityTracker object to watch the velocity of a motion.mVelocityTracker = VelocityTracker.obtain();}else {// Reset the velocity tracker back to its initial state.mVelocityTracker.clear();}// Add a user's movement to the tracker.mVelocityTracker.addMovement(event);break;case MotionEvent.ACTION_MOVE:mVelocityTracker.addMovement(event);// When you want to determine the velocity, call // computeCurrentVelocity(). Then call getXVelocity() // and getYVelocity() to retrieve the velocity for each pointer ID. mVelocityTracker.computeCurrentVelocity(1000);// Log velocity of pixels per second// Best practice to use VelocityTrackerCompat where possible.Log.d("", "X velocity: " + VelocityTrackerCompat.getXVelocity(mVelocityTracker, pointerId));Log.d("", "Y velocity: " + VelocityTrackerCompat.getYVelocity(mVelocityTracker,pointerId));break;case MotionEvent.ACTION_UP:case MotionEvent.ACTION_CANCEL:// Return a VelocityTracker object back to be re-used by others.mVelocityTracker.recycle();break;}return true;}
Note: 注意,应当在ACTION_MOVE事件内部计算速度,不要在ACTION_UP内部计算,因为在ACTION_UP内部计算所得到的X与Y的速度值都是0.