How can I listen for when a Button is pressed and released?
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.
onTouchListener is what you are looking for.
You will need to use the correct MotionEvent.
This will allow you to handle the different types of "touches".
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;
}
});