我为拖动视图创建了一个 onTouchListener。如果我使用 getRawX() 和 getRawY(),图片会平滑地拖动。但是问题是,当你放下第二个指针并抬起第一个指针时,图片会跳到第二个指针处。
这个 onTouchListener 试图通过跟踪 pointerId 来解决这个问题。但是在拖动 ImageView 时,ImageView 会非常不稳定地跳动,getX() 和 getY() 的值也会跳动。
我觉得我做得很正确。我不想为此编写自定义视图,因为我已经实现了 scaleGestureDetector 并编写了可工作的自定义 rotateGestureDetector。一切都正常运行,但我需要解决使用 getRawX() 和 getRawY() 时遇到的问题。
有人知道我做错了什么吗?
下面是我的 onTouchListener:
这个 onTouchListener 试图通过跟踪 pointerId 来解决这个问题。但是在拖动 ImageView 时,ImageView 会非常不稳定地跳动,getX() 和 getY() 的值也会跳动。
我觉得我做得很正确。我不想为此编写自定义视图,因为我已经实现了 scaleGestureDetector 并编写了可工作的自定义 rotateGestureDetector。一切都正常运行,但我需要解决使用 getRawX() 和 getRawY() 时遇到的问题。
有人知道我做错了什么吗?
下面是我的 onTouchListener:
final View.OnTouchListener onTouchListener = new View.OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
relativeLayoutParams = (RelativeLayout.LayoutParams) v.getLayoutParams();
final int action = event.getAction();
switch (action & MotionEvent.ACTION_MASK)
{
case MotionEvent.ACTION_DOWN:
{
final float x = event.getX();
final float y = event.getY();
// Where the user started the drag
lastX = x;
lastY = y;
activePointerId = event.getPointerId(0);
break;
}
case MotionEvent.ACTION_MOVE:
{
// Where the user's finger is during the drag
final int pointerIndex = event.findPointerIndex(activePointerId);
final float x = event.getX(pointerIndex);
final float y = event.getY(pointerIndex);
// Calculate change in x and change in y
final float dx = x - lastX;
final float dy = y - lastY;
// Update the margins to move the view
relativeLayoutParams.leftMargin += dx;
relativeLayoutParams.topMargin += dy;
v.setLayoutParams(relativeLayoutParams);
// Save where the user's finger was for the next ACTION_MOVE
lastX = x;
lastY = y;
v.invalidate();
break;
}
case MotionEvent.ACTION_UP:
{
activePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_CANCEL:
{
activePointerId = INVALID_POINTER_ID;
break;
}
case MotionEvent.ACTION_POINTER_UP:
{
// Extract the index of the pointer that left the touch sensor
final int pointerIndex = (action & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
if(pointerId == activePointerId)
{
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
lastX = (int) event.getX(newPointerIndex);
lastY = (int) event.getY(newPointerIndex);
activePointerId = event.getPointerId(newPointerIndex);
}
break;
}
}
return true;
}
};
image1.setOnTouchListener(onTouchListener);