如何检测按钮在android上按下和释放的时间 [英] How to detect when button pressed and released on android
问题描述
我想启动一个计时器,该计时器在第一次按下按钮时开始并在松开时结束(基本上我想测量一个按钮被按下的时间).我将在这两次使用 System.nanoTime() 方法,然后从最后一个数字中减去初始数字,以获得按住按钮时所用时间的测量值.
I would like to start a timer that begins when a button is first pressed and ends when it is released (basically I want to measure how long a button is held down). I'll be using the System.nanoTime() method at both of those times, then subtract the initial number from the final one to get a measurement for the time elapsed while the button was held down.
(如果您对使用 nanoTime() 以外的其他方法或其他测量按钮按下时间的方法有任何建议,我也愿意接受这些建议.)
(If you have any suggestions for using something other than nanoTime() or some other way of measuring how long a button is held down, I'm open to those as well.)
谢谢!安迪
推荐答案
使用 OnTouchListener 而不是 OnClickListener:
Use OnTouchListener instead of OnClickListener:
// this goes somewhere in your class:
long lastDown;
long lastDuration;
...
// this goes wherever you setup your button listener:
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
lastDown = System.currentTimeMillis();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
lastDuration = System.currentTimeMillis() - lastDown;
}
return true;
}
});
这篇关于如何检测按钮在android上按下和释放的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!