我正在计算ACTION_DOWN后按下按钮的时间长短,具体取决于按下的时间长度 - 我在ACTION_UP中以不同的方式响应按下。
问题在于,当我执行action_down(按下)时,它不会倒计时到最后,有时会这样做。
代码:
@Override
public boolean onTouch(final View v, final MotionEvent e) {
switch (e.getAction()) {
case MotionEvent.ACTION_DOWN:
still_down = false;
main_timer = new CountDownTimer(500, 4) {
@Override
public void onTick(long millisUntilFinished) {
Log.wtf("x", "timer: " + millisUntilFinished);
if ((int) millisUntilFinished < 100 && e.getAction() == MotionEvent.ACTION_DOWN) {
// above is where i detect that timer does not count down to 0, it stops at 119,107 etc
still_down = true;
}
}
@Override
public void onFinish() {
if (still_down) {
Log.wtf("x", "SHOW THE LARGE CARD!!!!!!!!!!!!!!!!!");
answer.setTextSize(50);
RelativeLayout.LayoutParams x = new RelativeLayout.LayoutParams(350, 500);
x.setMargins(margin_long_press_x1, margin_long_press_y1, 0, 0);
answer.setLayoutParams(x);
answer.requestLayout();
}
}
};
main_timer.start();
break;
case MotionEvent.ACTION_UP:
if (still_down) {
//image becomes small size again
main_timer.cancel();
} else {
action_on_single_tap( e);
}
break;
}
return true;
}
我在onTick()中放入一个日志,看到计时器并不总是计为0。
有没有办法计算Android中按下按钮的时间长短?我不知道其他任何方式。
答案 0 :(得分:1)
你走在正确的轨道上,看看它question几乎相同。
我发现这个最有帮助的
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_DOWN) {
this.start = System.currentTimeMillis();
} else if (event.getaction()==MotionEvent.ACTION_UP) {
this.end = System.currentTimeMillis();
}
}
答案 1 :(得分:1)
在onTick
中,if语句解释的操作始终为ACTION_DOWN,因为您可以在其中定义它。这就是为什么它总是在你设定的100门槛附近停止的原因。
如果您将倒数计时器声明移出onTouch
处理程序,则可以更轻松地查看它们是如何分开的。试试这个。
private static final long TIMER_DURATION = 500;
private CountDownTimer countDownTimer = new CountDownTimer(TIMER_DURATION, 4) {
@Override
public void onTick(long millisUntilFinished) {
// Don't need to do anything here
}
@Override
public void onFinish() {
Log.i("TimedTouchActivity", "Countdown timer finished!");
// answer.setTextSize(50);
}
};
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
Log.i("TimedTouchActivity", "Touch down");
countDownTimer.start();
} else if (action == MotionEvent.ACTION_UP) {
Log.i("TimedTouchActivity", "Touch up");
long eventDuration = event.getEventTime() - event.getDownTime();
if (eventDuration < TIMER_DURATION) {
Log.i("TimedTouchActivity", "Short");
countDownTimer.cancel();
// single click
} else {
Log.i("TimedTouchActivity", "Long");
// answer.setTextSize(20);
}
}
return true;
}