Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

listener for pressing and releasing a button

Tags:

android

view

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

like image 325
M'hamed Avatar asked Aug 02 '12 14:08

M'hamed


2 Answers

You can use a onTouchListener:

view.setOnTouchListener(new View.OnTouchListener() {        
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // PRESSED
                return true; // if you want to handle the touch event
            case MotionEvent.ACTION_UP:
                // RELEASED
                return true; // if you want to handle the touch event
        }
        return false;
    }
});
like image 95
sdabet Avatar answered Oct 19 '22 18:10

sdabet


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.

like image 11
Matt Avatar answered Oct 19 '22 20:10

Matt