使用motionevents模拟鼠标单击

时间:2017-02-17 21:45:03

标签: java android-studio

当我按下并且未移动应用程序中的鼠标垫时,我试图模拟鼠标单击。

  if(isConnected && out!=null){
                switch(event.getAction()){
                    case MotionEvent.ACTION_DOWN:
                        //save X and Y positions when user touches the TextView
                        initX =event.getX();
                        initY =event.getY();
                        mouseMoved=false;
                        break;
                    case MotionEvent.ACTION_MOVE:
                        disX = event.getX()- initX; //Mouse movement in x direction
                        disY = event.getY()- initY; //Mouse movement in y direction
                        /*set init to new position so that continuous mouse movement
                        is captured*/
                        initX = event.getX();
                        initY = event.getY();
                        if(disX !=0|| disY !=0){
                            out.println(disX +","+ disY); //send mouse movement to server
                        }
                        mouseMoved=true;
                        break;
                    case MotionEvent.ACTION_UP:
                        //consider a tap only if usr did not move mouse after ACTION_DOWN
                        if(!mouseMoved){
                               out.println(Constants.MOUSE_LEFT_CLICK);
                        }
                }
            }
            return true;
        }
    });
}

我试过这个,但我无法弄清楚为什么它不起作用。每次我点击鼠标垫,鼠标都会移动。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

使用if-else进行尝试,先按下按键,然后按住其他情况。

答案 1 :(得分:0)

我通过设置保证金解决了我的问题。

int max = 2 
int min = -2
case MotionEvent.ACTION_UP:
                        //consider a tap only if usr did not move mouse after ACTION_DOWN
                        if(disX <= max && disX >= min && disY <= max && disY >= min){
                            out.println(Constants.MOUSE_LEFT_CLICK);
                            mouseMoved=false;
                            break;
                        }
                }
            }
            return true;
        }