下面的代码段能使用户在屏幕上拖动一个对象。它记录了初始点的位置,计算点移动的距离,并将对象移动到新的位置。它正确的处理了这种情况:当第一个手指把控件拖到一个位置,然后按下第二个手指,且第二个手指与同一个控件上。当用户抬起第一个手指时,控件不会跑到第二个手指的位置同时第二个手指可以继续拖动控件。
- // The ‘active pointer’ is the one currently moving our object.
- private int mActivePointerId = INVALID_POINTER_ID;
- @Override
- public boolean onTouchEvent(MotionEvent ev) {
- // Let the ScaleGestureDetector inspect all events.
- mScaleDetector.onTouchEvent(ev);
- final int action = MotionEventCompat.getActionMasked(ev);
- switch (action) {
- case MotionEvent.ACTION_DOWN: {
- final int pointerIndex = MotionEventCompat.getActionIndex(ev);
- final float x = MotionEventCompat.getX(ev, pointerIndex);
- final float y = MotionEventCompat.getY(ev, pointerIndex);
- // Remember where we started (for dragging)
- mLastTouchX = x;
- mLastTouchY = y;
- // Save the ID of this pointer (for dragging)
- mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
- break;
- }
- case MotionEvent.ACTION_MOVE: {
- // Find the index of the active pointer and fetch its position
- final int pointerIndex =
- MotionEventCompat.findPointerIndex(ev, mActivePointerId);
- final float x = MotionEventCompat.getX(ev, pointerIndex);
- final float y = MotionEventCompat.getY(ev, pointerIndex);
- // Only move if the ScaleGestureDetector isn't processing a gesture.
- if (!mScaleDetector.isInProgress()) {
- // Calculate the distance moved
- final float dx = x - mLastTouchX;
- final float dy = y - mLastTouchY;
- mPosX += dx;
- mPosY += dy;
- invalidate();
- }
- // Remember this touch position for the next move event
- mLastTouchX = x;
- mLastTouchY = y;
- break;
- }
- case MotionEvent.ACTION_UP: {
- mActivePointerId = INVALID_POINTER_ID;
- break;
- }
- case MotionEvent.ACTION_CANCEL: {
- mActivePointerId = INVALID_POINTER_ID;
- break;
- }
- case MotionEvent.ACTION_POINTER_UP: {
- final int pointerIndex = MotionEventCompat.getActionIndex(ev);
- final int pointerId = MotionEventCompat.getPointerId(ev, pointerIndex);
- if (pointerId == mActivePointerId) {
- // This was our active pointer going up. Choose a new
- // active pointer and adjust accordingly.
- final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
- mLastTouchX = MotionEventCompat.getX(ev, newPointerIndex);
- mLastTouchY = MotionEventCompat.getY(ev, newPointerIndex);
- mActivePointerId = MotionEventCompat.getPointerId(ev, newPointerIndex);
- }
- break;
- }
- }
- return true;
- }