Search code examples
androidbuttoncoordinatesactionlistenermotionevent

Check Button Leave, Android


Here is the problem...

What I Try to do :

I have a button in my Fragment, the user presses it.

And I would like to know when user's finger moves out of the button.

What I have managed to do :

private Button btn;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ...

    btn = (Button) view.findViewById(R.id.btn);
    btn.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                // TODO do something
            } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
                checkIfFingerStillOnButton(event);
            }
            return true;
        }
    });
}

public void checkIfFingerStillOnButton(MotionEvent event) {
    boolean result = false;

    // Button limits
    float coordLeft = btn.getLeft();
    float coordRight = btn.getRight();
    float coordTop = btn.getTop();
    float coordBot = btn.getBottom();

    // Finger coordinates
    float X = event.getX();
    float Y = event.getY();

    if (X>coordLeft && X<coordRight && Y<coordTop && Y>coordBot) { result = true; }
}

Result so far :

The coordinates returned by those functions aren't what I expected.

Here is what I get when clicking in the middle of the button :

Left=312.0, Right=672.0, Top=670.0, Bottom=1030.0, 
X=189.0, Y=194.17029 | result=false

Thank you for your help !


Solution

  • Here is the way I solved it :

    boolean result = false;
    int[] location  = new int[2];
    btnStartGame.getLocationOnScreen(location);
    
    // Finger coordinates
    float X = event.getRawX();
    float Y = event.getRawY();
    
    // Button limits
    float coordLeft = location[0];
    float coordRight = location[0] + btnStartGame.getWidth();
    float coordTop = location[1];
    float coordBot = location[1] + btnStartGame.getHeight();
    
    if (X>coordLeft && X<coordRight && Y>coordTop && Y<coordBot) {
        result = true;
        btnStartGame.setText("true");
    } else {
        btnStartGame.setText("false");
    }
    

    I hope it will help someone else.