这是我个人的看法,要学好android触控,了解MotionEvent是必要,对所用的MotionEvent常用的API要比较深入的了解.
下面是我个人的学习过程记录:
android.view.MotionEvent
MotionEvent源代码可以在ocs看到,当然你也可以在SDK中下载源代码,或者其他地方,如:
MotionEvent事件对象
一般我们是在View的onTouchEvent方法中处理MotionEvent对象的.
public boolean onTouchEvent(MotionEvent event)
在这里我们需要从一个MotionEvent对象中获得哪些信息呢?
(1)首先应该是事件的类型吧?
可以通过getAction(),在android2.2之后加入多点触控支持之后使用getActionMasked()方法.
这两个方法的区别见后文.
主要的事件类型有:
ACTION_DOWN: 表示用户开始触摸.
ACTION_MOVE: 表示用户在移动(手指或者其他)
ACTION_UP:表示用户抬起了手指
ACTION_CANCEL:表示手势被取消了,一些关于这个事件类型的讨论见:http://stackoverflow.com/questions/11960861/what-causes-a-motionevent-action-cancel-in-android
还有一个不常见的:
ACTION_OUTSIDE: 表示用户触碰超出了正常的UI边界.
但是对于多点触控的支持,Android加入了以下一些事件类型.来处理,如另外有手指按下了,
有的手指抬起来了.等等:
ACTION_POINTER_DOWN:有一个非主要的手指按下了.
ACTION_POINTER_UP:一个非主要的手指抬起来了
(2)事件发生的位置,x,y轴
getX() 获得事件发生时,触摸的中间区域在屏幕的X轴.
getY() 获得事件发生时,触摸的中间区域在屏幕的X轴.
在多点触控中还可以通过:
getX(int pointerIndex) ,来获得对应手指事件的发生位置. 获得Y轴用getY(int pointerIndex)
(3)其他属性
getEdgeFlags():当事件类型是ActionDown时可以通过此方法获得,手指触控开始的边界. 如果是的话,有如下几种值:EDGE_LEFT,EDGE_TOP,EDGE_RIGHT,EDGE_BOTTOM
一些讨论
(1)首先是MotionEvent 中getAction()与getActionMasked()的区别:
首先看代码:
01 |
/** |
02 |
* Bit mask of the parts of the action code that are the action itself. |
03 |
*/ |
04 |
public static final int ACTION_MASK = 0xff ; |
05 |
06 |
/** |
07 |
* Return the kind of action being performed. |
08 |
* Consider using {<a href="http://my.oschina.net/link1212" target="_blank" rel="nofollow">@link</a> #getActionMasked} and {<a href="http://my.oschina.net/link1212" target="_blank" rel="nofollow">@link</a> #getActionIndex} to retrieve |
09 |
* the separate masked action and pointer index. |
10 |
* @return The action, such as {<a href="http://my.oschina.net/link1212" target="_blank" rel="nofollow">@link</a> #ACTION_DOWN} or |
11 |
* the combination of {<a href="http://my.oschina.net/link1212" target="_blank" rel="nofollow">@link</a> #ACTION_POINTER_DOWN} with a shifted pointer index. |
12 |
*/ |