gpt4 book ai didi

java - MotionEvent.ACTION_DOWN 在 Android 中不起作用

转载 作者:行者123 更新时间:2023-12-01 05:11:11 28 4
gpt4 key购买 nike

我编写了一个使用拖动和缩放的 Android 应用程序。但是当我编程 Touch 类时,MotionEvent.ACTION_DOWNMotionEvent.ACTION_POINTER_DOWNMotionEvent.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);
}

最佳答案

有必要使用switch case语句吗?这对你来说可能更容易阅读,但是当我这样做时 >>

    if (event.getAction() == MotionEvent.ACTION_UP){

} else if (event.getAction() == MotionEvent.ACTION_DOWN) {

} else if (event.getAction() == MotionEvent.ACTION_MOVE) {

}

它工作得很好。另外,您应该在 case 语句中添加日志调用,以查明您的 onTouch 是否被调用,以及它执行和未执行的情况。您还可以记录掩码和事件代码传入的值吗?这些都会有所帮助。

关于java - MotionEvent.ACTION_DOWN 在 Android 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12013882/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com