Android 用于按下和释放按钮的侦听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11779082/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
listener for pressing and releasing a button
提问by M'hamed
How can I listen for when a Button
is pressed and released?
Button
按下和释放a 时如何收听?
回答by sdabet
You can use a onTouchListener
:
您可以使用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;
}
});
回答by Matt
The answer given by fiddleris correct for generic views.
fiddler给出的答案对于通用视图是正确的。
For a Button
, you should return false
from the touch handler always:
对于 a 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;
}
});
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.
如果您返回,true
您将绕过按钮的常规触摸处理。这意味着您将失去按下按钮和触摸波纹的视觉效果。此外,Button#isPressed()
将false
在实际按下按钮时返回。
The button's regular touch processing will ensure that you get the follow-up events even when returning false
.
按钮的常规触摸处理将确保您即使在返回时也能获得后续事件false
。
回答by prolink007
onTouchListener
is what you are looking for.
onTouchListener
就是你要找的。
You will need to use the correct MotionEvent
.
您将需要使用正确的MotionEvent
.
This will allow you to handle the different types of "touches".
这将允许您处理不同类型的“触摸”。