我编写了一个使用拖放功能的Android应用程序。但是,当我编写Touch
课时,MotionEvent.ACTION_DOWN
,MotionEvent.ACTION_POINTER_DOWN
和MotionEvent.ACTION_MOVE
无效。如何修复我的代码?
触摸课程:
private static final int NONE = 0;
private static final int DRAG = 1;
private static final int ZOOM = 2;
private static final float MAX_ZOOM = 3f;
private static final float MIN_ZOOM = 3f;
public boolean onTouch(View view, MotionEvent event) {
int mode = NONE;
float oldDistance = 1f;
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
PointF start = new PointF();
PointF mid = new PointF();
ImageView imageView = (ImageView)view;
switch(event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDistance = spacing(event);
if(oldDistance > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
break;
case MotionEvent.ACTION_MOVE:
if(mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
}
else if(mode == ZOOM) {
float newDistance = spacing(event);
if(newDistance > 10f) {
matrix.set(savedMatrix);
float scale = newDistance / oldDistance;
float[] values = new float[9];
matrix.getValues(values);
float currentScale = values[Matrix.MSCALE_X];
if(scale * currentScale > MAX_ZOOM)
scale = MAX_ZOOM / currentScale;
else if (scale * currentScale < MIN_ZOOM)
scale = MIN_ZOOM / currentScale;
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
imageView.setImageMatrix(matrix);
return true;
}
private float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
private void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
答案 0 :(得分:0)
是否有必要使用switch case语句?你可能更容易阅读,但当我这样做时> gt;&gt;
if (event.getAction() == MotionEvent.ACTION_UP){
} else if (event.getAction() == MotionEvent.ACTION_DOWN) {
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
}
它运作得很好。此外,您应该在case case语句中添加日志调用,以查明是否正在调用onTouch,以及它执行和不执行的情况。您还可以记录掩码和事件代码传递的值吗?那些都会有所帮助。