Android 如何计算释放按钮后经过的时间?
我试图做一个简单的莫尔斯电码翻译。我可以计算用户按下按钮以生成点或破折号的时间,但我无法计算用户释放按钮后经过的时间-经过的时间将允许我通过计时符号之间的间距来确定它是否为新字母/单词Android 如何计算释放按钮后经过的时间?,android,time,Android,Time,我试图做一个简单的莫尔斯电码翻译。我可以计算用户按下按钮以生成点或破折号的时间,但我无法计算用户释放按钮后经过的时间-经过的时间将允许我通过计时符号之间的间距来确定它是否为新字母/单词 public void btnPressed(View view) { button.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View
public void btnPressed(View view)
{
button.setOnTouchListener(new View.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;
//Timer starts when the button is released.
start = System.currentTimeMillis();
}
return false;
}
});
//This is where attempt to calculate the elapsed time.
stop = System.currentTimeMillis() - start;
它确实返回一个时间-问题是经过的时间只有几毫秒长。有没有更简单的方法来解决这个问题?你似乎对如何解决这个问题感到困惑。
在按钮
onTouch
处理程序中,您似乎为其设置了一个新的处理程序。这是一条容易出错的复杂路径
最简单的方法是只使用一个onTouch
回调
这一个记录了按钮按下和按下的时间
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// we have pressed, record the time
pressTime = System.currentTimeMillis();
// check how long it has been since last release
timeSinceLastRelease = System.currentTimeMillis() - releaseTime;
} else if (event.getAction() == MotionEvent.ACTION_UP) {
// we have released, record the time
releaseTime = System.currentTimeMillis();
// check how long it has been since last press
timeSinceLastPress = System.currentTimeMillis() - pressTime;
}
return false;
}
将以下代码放入创建时的
onCreate
中,而不是btnPressed
button.setOnTouchListener(new View.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;
//Timer starts when the button is released.
start = System.currentTimeMillis();
}
return false;
}
代码中发生的事情是您的
touchListner
只有在单击按钮后才能工作。将其放入onCreate中将使其始终工作。按下按钮后是否设置onTouchListener?尝试在onCreate方法中设置它。然后,您可以在lastDuration=System.currentTimeMillis()-lastDown之后执行逻辑代码>行。似乎这就是问题所在。我怀疑自己在设计上有什么问题,但无法弄清楚到底是什么问题。谢谢你的意见。