我有一个View,其中包含一个recyclerView。我想用两个手指移动这个视图。遵循官方文档this。这有助于我用一根手指移动视图。现在,我只想用两个手指移动视图。我已经读到可以通过实现MotionEvent.ACTION_POINTER_DOWN来实现,但是我不知道如何管理指针。 下面是我的代码:
private View.OnTouchListener onTouchListener() {
return new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final int pointerIndex1,pointerIndex2;
// Let the ScaleGestureDetector inspect all events.
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
pointerIndex1 = event.getActionIndex();
final float x = event.getX(pointerIndex1);
final float y = event.getY(pointerIndex1);
// Remember where we started (for dragging)
mLastTouchX = x;
mLastTouchY = y;
// Save the ID of this pointer (for dragging)
mActivePointerId = event.getPointerId(0);
break;
}
case MotionEvent.ACTION_POINTER_DOWN:
pointerIndex2 = event.getActionIndex();
break;
case MotionEvent.ACTION_MOVE: {
// Find the index of the active pointer and fetch its position
final int pointerIndex = event.findPointerIndex(mActivePointerId);
final float x = event.getX(pointerIndex);
final float y = event.getY(pointerIndex);
// Calculate the distance moved
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
lin_container.setTranslationX(mPosX);
lin_container.setTranslationY(mPosY);
// 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 = event.getActionIndex();
final int pointerId = event.getPointerId(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 = event.getX(newPointerIndex);
mLastTouchY = event.getY(newPointerIndex);
mActivePointerId = event.getPointerId(newPointerIndex);
}
break;
}
}
return true;
}
};
}
有人可以告诉我如何实现吗?
答案 0 :(得分:1)
如果要用两个手指仅移动视图,只需添加指针计数检查即可:
final ImageView imageView;
private float startX;
private float startY;
private float startTranslationX;
private float startTranslationY;
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
startTranslationX = imageView.getTranslationX();
startTranslationY = imageView.getTranslationY();
startX = event.getX();
startY = event.getY();
break;
}
case MotionEvent.ACTION_MOVE: {
if (event.getPointerCount() == 2) {
imageView.setTranslationX(startTranslationX + event.getX() - startX);
imageView.setTranslationY(startTranslationY + event.getY() - startY);
}
break;
}
}
return true;
}