[Android分享] 使用触摸手势(二)

来源:互联网 发布:java连接数据库的代码 编辑:程序博客网 时间:2024/05/20 18:18
原文链接:http://developer.android.com/training/gestures/movement.html

追踪移动

当前触摸的位置、压力或大小发生变化时,一个ACTION_MOVE的onTouchEvent()事件将被触发。

因为手指触摸并不是最精确的互动形式,检测触摸事件往往是基于更多的移动动作,而不是简单的触碰。为了帮助应用程序区分基于运动的手势和非运动的手势,Android引入了一个“touch slop”的概念。“touch slop”是指一个触摸动作被认为是一个移动动作移动的单位距离。

有几种不同的方法来跟踪运动的手势,选用哪种方法取决于应用程序的需求。

1.一个移动操作的起始和结束位置(例如把一个物体从A点移动到B点)。
2.由X和Y坐标确定的移动方向。
3.移动轨迹。能够通过调用getHistorySize()方法获得手势轨迹的大小。可以通过调用getHistorical获得轨迹中每个事件的位置、大小、时间和压力。当要渲染手指移动,历史记录是很有用的,例如触摸绘图。
4.在屏幕上移动的速度。

跟踪速度

可以简单的获取移动手势通过移动的距离和方向。但速度在跟踪手势动作或确定某个手势是否发生时,也是一个决定因素。为了使计算速度更容易,Android在Support Library库中提供了VelocityTracker和VelocityTrackerCompat类。VelocityTracker帮助你获得触摸事件的速度。当速度是决定某个手势是否发生的标准时,这是很有用的。
?
代码片段,双击复制
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
publicclass MainActivity extendsActivity {
   privatestatic final String DEBUG_TAG = "Velocity";
        ...
   privateVelocityTracker mVelocityTracker = null;
   @Override
   publicboolean onTouchEvent(MotionEvent event) {
        intindex = event.getActionIndex();
        intaction = event.getActionMasked();
        intpointerId = event.getPointerId(index);
 
        switch(action) {
            caseMotionEvent.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;
            caseMotionEvent.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;
            caseMotionEvent.ACTION_UP:
            caseMotionEvent.ACTION_CANCEL:
                // Return a VelocityTracker object back to be re-used by others.
                mVelocityTracker.recycle();
                break;
        }
        returntrue;
   }
}
原创粉丝点击