JK7
JK7

Reputation: 125

simulate mouse click with motionevents

I am trying to simulate a mouse click when a mousepad in the app is pressed and not moved.

  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;
        }
    });
}

I have tried this, but I can't figure out why it won't work. Every time I click on the mousepad the mouse moves. How can I solve this?

Upvotes: 1

Views: 296

Answers (2)

JK7
JK7

Reputation: 125

I solved my problem by setting a margin.

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;
        }

Upvotes: 0

Patricia
Patricia

Reputation: 2865

try it with an if-else and put the pressing first and the moving in the else-case.

Upvotes: 1

Related Questions