如何监听 Button
的按下和释放事件?
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;
}
});
fiddler的回答适用于通用视图。
对于Button
,您应该始终从触摸处理程序中返回false
:
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;
}
});
true
,则将绕过按钮的常规触摸处理。这意味着您将失去按下按钮和触摸涟漪的视觉效果。此外,当实际按下按钮时,Button#isPressed()
将返回false
。false
,按钮的常规触摸处理也会确保您获得后续事件。
MotionEvent.ACTION_CANCEL
事件也应该被处理为按钮释放事件(与ACTION_UP
相同),因为当您按下按钮后执行某些手势时会触发它(此时不会触发ACTION_UP
事件)。 - user2137020ACTION_BUTTON_PRESS
和ACTION_BUTTON_RELEASE
。认为这两个可能包含DOWN
、UP
和CANCEL
操作。 - David LordonClickListener
。 - Konstantin KonopkoACTION_UP
情况下添加v.performClick()
,或者只需返回false
。 - hanswim