androidviewgesturepressed

How to detect if touch is released on top of custom Android view?


When my view is in pressed state and the location of a touch event leaves the view, I want the view to get notified. I also want to get notified when the touch location re-enters my view whilst still in pressed state.

My view extends View, and currently implements this method:

public boolean onTouchEvent(MotionEvent event) {
    boolean result = gestureDetector.onTouchEvent(event);
    if (!result) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            animate().scaleX(1).scaleY(1).setDuration(100).start();
            performClick();
        }
    }
    return result;
}

gestureDetector refers to an instance of this class:

class GestureListener extends GestureDetector.SimpleOnGestureListener {
    public boolean onDown(MotionEvent e) {
        animate().scaleX(0.9f).scaleY(0.9f).setDuration(100).start();
        return true;
    }
}

This works just fine, but when a touch is pressed down and released outside of my view, MotionEvent.ACTION_UP still gets fired (and thus performClick() too), which is not the behaviour I'm looking for. I have tried many other actions in MotionEvent, but nothing does this.

Any ideas?


Solution

  • Change your if statement to include the dimensions of the button

    boolean inX == event.getX() >= myButton.getX() && event.getX() <= myButton.getX()+myButton.getWidth();
    
    boolean inY == event.getY() >= myButton.getY() && event.getY() <= myButton.getY()+myButton.getWidth();
    
    if (event.getAction() == MotionEvent.ACTION_UP && inX && inY) {
           // do cool stuff