是否可以将多点触控限制为只有两个手指?

问题描述

在我的应用上同时按下三个或更多手指时,我收到以下错误

'JNI DETECTED ERROR IN APPLICATION: JNI CallVoidMethodV called with pending exception java.lang.Arrayindexoutofboundsexception: length=3; index=3
        at boolean

以下代码控制多点触控:

    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getActionMasked();
        int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_ID_MASK) >> MotionEvent.ACTION_POINTER_ID_SHIFT;
        int pointerID = event.getPointerId(pointerIndex);
        int[] touchX = new int[event.getPointerCount()];

        for(int i = 0 ; i < event.getPointerCount() ; i++){
            touchX[i] = (int) event.getX(i);
        }

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                if (touchX[0] < screenX / 2) {
                    astronaut.isGoingUp = true;
                }
                break;
            case MotionEvent.ACTION_UP:
                astronaut.isGoingUp = false;
                if (touchX[0] > screenX / 2) {
                    astronaut.toShot++;
                }
                break;
            case MotionEvent.ACTION_POINTER_DOWN:
                if(touchX[pointerID] < screenX / 2) {
                    astronaut.isGoingUp = true;
                }
            case MotionEvent.ACTION_POINTER_UP:
                if(touchX[pointerID] > screenX / 2){
                    astronaut.toShot++;
                }
            default:
                break;

        }
        return true;
    }

我猜它与 event.getPointerCount() 或 for 循环有关。 我想知道当它崩溃超过两个手指时我做错了什么,除了它完全按照预期工作。

谢谢

解决方法

您可以使用 MotionEvent.ACTION_POINTER_DOWN 掩码过滤多点触摸的动作,如果手指数大于 2,则返回。

getPointerCount() 返回一次接触的装配工数量。

public boolean onTouchEvent(MotionEvent event) {

    // More than one down touches
    if ((action & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_POINTER_DOWN) { 
        int count = event.getPointerCount(); // Number of touched 'fingers' 
        if (count > 2) // return if greater than 2 fingers
            return true;
    }
    
    // Your code here is for one or two fingers
    
}

    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...