如何判断MotionEvent.ACTION_UP上已发布哪个鼠标按钮

时间:2018-03-31 16:42:42

标签: android

我的鼠标连接到Android 6.0平板电脑。我正试图在我的onTouch中听左右鼠标按下并释放事件。按下鼠标按钮时工作正常,但释放鼠标按钮时getButtonState()总是返回0,所以我无法分辨哪个按钮(左或右?)已被释放。

这是我的代码:

@Override
public boolean onTouch(View v, MotionEvent event) {

    if(event.getSource() == InputDevice.SOURCE_MOUSE) {

        int action = event.getActionMasked();   
        int mouseButton = event.getButtonState();

        Log.v("Test", "Action: " + action + " MouseButton: " + mouseButton);            
        return true;
    }

    return false;
}

Action为1(即ACTION_UP)时,mouseButton始终为0,因此我无法确定是否刚刚释放了鼠标左键或右键。当Action为0(即ACTION_DOWN)时,mouseButton已正确设置为BUTTON_PRIMARYBUTTON_SECONDARY

那么有人知道如何区分ACTION_UP上的鼠标左键和右键吗?

1 个答案:

答案 0 :(得分:1)

要回答我自己的问题,isButtonPressed()是解决这个问题的关键。通过监视isButtonPressed()并在从InputDevice.SOURCE_MOUSE获得MotionEvent时缓存其结果,您可以判断哪个按钮已被按下或释放。您还需要小心将这些观察限制为ACTION_UPACTION_DOWN,因为当一个按钮已经关闭并且另一个按钮被按下或释放时,您就赢了'得到ACTION_DOWNACTION_UP,但只要有一个按钮就会生成ACTION_MOVE个事件。

因此,就代码而言,解决方案可能如下所示:

private static boolean mLeftDown = false, mRightDown = false, mMiddleDown = false;

@Override
public boolean onTouch(View v, MotionEvent event) {

        if(event.getSource() == InputDevice.SOURCE_MOUSE) {

            boolean leftDown = event.isButtonPressed(MotionEvent.BUTTON_PRIMARY);
            boolean rightDown = event.isButtonPressed(MotionEvent.BUTTON_SECONDARY);
            boolean middleDown = event.isButtonPressed(MotionEvent.BUTTON_TERTIARY);

            if(leftDown != mLeftDown) {
                // left button pressed or released
                mLeftDown = leftDown;
            }

            if(rightDown != mRightDown) {
                // right button pressed or released
                mRightDown = rightDown;
            }                   

            if(middleDown != mMiddleDown) {
                // middle button pressed or released
                mMiddleDown = middleDown;
            }

            return true;
        }

        return false;
}

这在Android 6.0上运行良好。