listener for pressing and releasing a button

Viewed 38332

How can I listen for when a Button is pressed and released?

3 Answers

The answer given by fiddler is correct for generic views.

For a Button, you should return false from the touch handler always:

button.setOnTouchListener(new View.OnTouchListener() {      
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // PRESSED
                break;
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
                // RELEASED
                break;
        }
        return false;
    }
});

If you return true you will circumvent the button's regular touch processing. Which means you will loose the visual effects of pressing the button down and the touch ripple. Also, Button#isPressed() will return false while the button is actually pressed.

The button's regular touch processing will ensure that you get the follow-up events even when returning false.

Related