多点触摸手势是当多个指针(手指)同时触摸屏幕时。本课介绍如何检测涉及多个指针的手势。
请参阅以下相关资源:
跟踪多个指针
当多个指针同时触摸屏幕时,系统会生成以下触摸事件:
- ACTION_DOWN - 触摸屏幕的第一个指针。这开始了手势。这个指针的指针数据总是在索引0中MotionEvent。
- ACTION_POINTER_DOWN - 用于超出第一个屏幕的额外指针。该指针的指针数据位于返回的索引处getActionIndex()。
- ACTION_MOVE - 新闻手势发生变化。
- ACTION_POINTER_UP - 当非主要指针上升时发送。
- ACTION_UP - 最后一个指针离开屏幕时发送。
MotionEvent通过每个指针的索引和ID来跟踪各个指针内的指针:
- 索引:A MotionEvent有效地存储有关阵列中每个指针的信息。指针的索引是它在这个数组中的位置。大多数MotionEvent用于与指针进行交互的方法都将指针索引作为参数,而不是指针ID。
- ID:每个指针还有一个ID映射,在整个触摸事件中保持不变,以便跟踪整个手势中的单个指针。
单个指针在运动事件中出现的顺序未定义。因此,指针的索引可以从一个事件改变到下一个事件,但只要指针保持活动状态,指针的指针ID就保证保持不变。使用该 getPointerId()方法获取指针的ID以跟踪手势中所有后续动作事件的指针。然后,对于连续运动事件,请使用该findPointerIndex()方法获取该运动事件中给定指针ID的指针索引。例如:
private int mActivePointerId;
public boolean onTouchEvent(MotionEvent event) {
....
// Get the pointer ID
mActivePointerId = event.getPointerId(0);
// ... Many touch events later...
// Use the pointer ID to find the index of the active pointer
// and fetch its position
int pointerIndex = event.findPointerIndex(mActivePointerId);
// Get the pointer's current position
float x = event.getX(pointerIndex);
float y = event.getY(pointerIndex);
}
获取MotionEvent的操作
您应该始终使用该方法 getActionMasked()(或更好的兼容版本 MotionEventCompat.getActionMasked())来检索a的操作 MotionEvent。与旧的getAction() 方法不同,它getActionMasked()被设计用于处理多个指针。它返回正在执行的被屏蔽动作,不包括指针索引位。然后您可以使用 getActionIndex()返回与该操作关联的指针的索引。这在下面的片段中进行了说明。
注意:这个例子使用这个 MotionEventCompat 类。该课程位于 支持库中。您应该使用 MotionEventCompat为广泛的平台提供最佳支持。请注意,MotionEventCompat是不是为替代MotionEvent类。相反,它提供了静态实用程序方法,您可以通过它传递MotionEvent对象以便接收与该事件相关的所需操作。
int action = MotionEventCompat.getActionMasked(event);
// Get the index of the pointer associated with the action.
int index = MotionEventCompat.getActionIndex(event);
int xPos = -1;
int yPos = -1;
Log.d(DEBUG_TAG,"The action is " + actionToString(action));
if (event.getPointerCount() > 1) {
Log.d(DEBUG_TAG,"Multitouch event");
// The coordinates of the current screen contact, relative to
// the responding View or Activity.
xPos = (int)MotionEventCompat.getX(event, index);
yPos = (int)MotionEventCompat.getY(event, index);
} else {
// Single touch event
Log.d(DEBUG_TAG,"Single touch event");
xPos = (int)MotionEventCompat.getX(event, index);
yPos = (int)MotionEventCompat.getY(event, index);
}
...
// Given an action int, returns a string description
public static String actionToString(int action) {
switch (action) {
case MotionEvent.ACTION_DOWN: return "Down";
case MotionEvent.ACTION_MOVE: return "Move";
case MotionEvent.ACTION_POINTER_DOWN: return "Pointer Down";
case MotionEvent.ACTION_UP: return "Up";
case MotionEvent.ACTION_POINTER_UP: return "Pointer Up";
case MotionEvent.ACTION_OUTSIDE: return "Outside";
case MotionEvent.ACTION_CANCEL: return "Cancel";
}
return "";
}
有关多点触控和一些示例的更多讨论,请参阅“ 拖动和缩放 ”课程 。
Lastest Update:2018.04.25
联系我
QQ:94297366
微信打赏:https://pan.baidu.com/s/1dSBXk3eFZu3mAMkw3xu9KQ
公众号推荐:
转载于:https://blog.51cto.com/4789781/2124893