Android多点触控 - TouchMove事件

时间:2016-05-31 18:15:49

标签: java android input multi-touch touchscreen

我正在尝试获取指针列表,无论它们是否已关闭,以及它们在屏幕上以像素为单位的位置,因此我可以将桌面游戏移植到android。为此,我写了这个onTouch处理程序。

private boolean onTouch(View v, MotionEvent e)
{
    final int action = e.getActionMasked();

    switch (action)
    {
        case MotionEvent.ACTION_DOWN:
            surfaceView.queueEvent(() -> postTouchEvent(FINGER_0, true, e.getX(), e.getY()));
            break;

        case MotionEvent.ACTION_UP:
            surfaceView.queueEvent(() -> postTouchEvent(FINGER_0, false, e.getX(), e.getY()));
            break;

        case MotionEvent.ACTION_POINTER_DOWN:
        case MotionEvent.ACTION_POINTER_UP:
        {
            final int index = e.getActionIndex();
            final int finger = index + 1;

            if (finger < FINGER_1 || finger > FINGER_9)
                break;

            final boolean isDown = action == MotionEvent.ACTION_POINTER_DOWN;
            surfaceView.queueEvent(() -> postTouchEvent(finger, isDown, e.getX(), e.getY()));
        }
        break;

        case MotionEvent.ACTION_MOVE:
            for (int i = 0; i < e.getPointerCount(); i++)
            {
                final int finger = i + 1;

                if (finger < FINGER_0 || finger > FINGER_9)
                    break;

                surfaceView.queueEvent(() ->
                        postTouchEvent(finger, true, e.getX(finger - 1), e.getY(finger - 1)));
            }
            for (int i = e.getPointerCount(); i < FINGER_9; i++)
            {
                final int finger = i + 1;
                surfaceView.queueEvent(() -> postTouchEvent(finger, false, 0, 0));
            }
            break;
    }

    return true;
}

然而问题是ACTION_MOVE事件,我得到一个IllegalArgumentException来访问我的索引ID。只有当我一次在屏幕上点击三个或更多手指时才会发生这种情况,但这仍然是一个问题。例外情况如下。

FATAL EXCEPTION: GLThread 61026
Process: com.shc.silenceengine.tests.android, PID: 23077
java.lang.IllegalArgumentException: pointerIndex out of range
    at android.view.MotionEvent.nativeGetAxisValue(Native Method)
    at android.view.MotionEvent.getX(MotionEvent.java:2014)
    at com.shc.silenceengine.backend.android.AndroidInputDevice.lambda$onTouch$14(AndroidInputDevice.java:228)
    at com.shc.silenceengine.backend.android.AndroidInputDevice.access$lambda$6(AndroidInputDevice.java)
    at com.shc.silenceengine.backend.android.AndroidInputDevice$$Lambda$7.run(Unknown Source)
    at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1462)
    at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1239)

我不知道为什么我收到错误,因为我只在e.getPointerCount()进行for循环,因此索引不可能超出代码。

我不想跟踪指针ID,我只想要一个原始的指针列表,这些事件在我的引擎列表中组成到下一帧。

有人指出我的问题在哪里吗?

1 个答案:

答案 0 :(得分:1)

您正在从一个单独的(稍后的)线程调用e.getX()e.getY() - MotionEvent对象的内部状态可能在onTouch()回调和执行之间发生了变化线程。

您应该只假设MotionEvent对象在onTouch()方法期间有效,并检索getX()getY()的值以在之前传递给线程方法退出。