本文共 2549 字,大约阅读时间需要 8 分钟。
原文地址:
多点触控是指多个手指同时触摸屏幕的情况。这节课主要学习如何检测多点触控手势。
当多根手指同时触碰到屏幕时,系统会产生以下触摸事件:
我们可以通过每一个触控点对应的索或ID来追踪对象中的每一个触控点:
每个触控点的出现顺序是不固定的。因此,触控点的索引可以由事件转移到下一个索引,但是触控点的ID始终保持为一个常量。使用方法可以获得指定触控点的ID,因此可以在余下的手势事件中还可以继续保持与这个触控点的联系。使用方法可以根据指定的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);}
使用方法可以获取的活动。与getAction()方法不同,适用于多个触控点。它会返回正在执行的活动。你可以使用方法获得与之相关联的触控点的索引。下面的代码演示了这个过程:
Note: 示例中使用了类。这个类位于支持库中。你应该使用该类以便提供良好的向后兼容性。注意,类并不可以替代类。这个类提供了一个实用的静态方法,可以将对象所关联的活动提取出来。
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 descriptionpublic 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 "";}
有关多点触控的更多信息,可以参见课程.
转载地址:http://sfebm.baihongyu.com/