How can I listen for when a Button
is pressed and released?
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;
}
});
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With