我有一些在运行时创建并添加到FrameLayout
的视图。视图可以移动onTouchEvent
。到目前为止,我能够提出意见。但是,它们没有正常运转。我的意思是,第一次,当他们被移动时,他们一起移动。但是,当它们第二次移动时,手指和视图之间的距离会增加,并且它们会移动到手指指向之外的其他点。我没弄到错误的地方。以下是我的代码:
@Override
public boolean onTouch(View v, MotionEvent event) {
final int X = (int) event.getRawX();
final int Y = (int) event.getRawY();
boolean result = v.onTouchEvent(event);
switch (event.getAction() & MotionEventCompat.getActionMasked(event)) {
case MotionEvent.ACTION_DOWN: {
Log.e("CircleTest", "ACTION_DOWN");
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) v
.getLayoutParams();
deltaX = X - params.leftMargin;
deltaY = Y - params.rightMargin;
// Save the ID of this pointer
mActivePointerId = event.getPointerId(0);
break;
}
case MotionEvent.ACTION_UP:
mActivePointerId = INVALID_POINTER_ID;
break;
case MotionEvent.ACTION_CANCEL:
mActivePointerId = INVALID_POINTER_ID;
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP: {
final int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
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;
}
}
case MotionEvent.ACTION_MOVE: {
Log.e("CircleTest", "ACTION_MOVE");
final int pointerIndex1 = event.findPointerIndex(mActivePointerId);
final float x = event.getX(pointerIndex1);
final float y = event.getY(pointerIndex1);
final float dx = x - mLastTouchX;
final float dy = y - mLastTouchY;
mPosX += dx;
mPosY += dy;
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) v
.getLayoutParams();
params.leftMargin = X - deltaX;
params.topMargin = Y - deltaY;
v.setLayoutParams(params);
mLastTouchX = x;
mLastTouchY = y;
break;
}
default:
return result;
}
main.invalidate();
return false;
}
//**main** refers to the frame layout in which views are added.