我正在开发一款带有开始按钮的秒表应用程序。单击开始按钮后,计时器启动,按钮文本更新为暂停。单击“暂停”后,计时器停止,按钮文本更改为“恢复”。当我点击继续时,我希望计时器从它暂停的位置开始,但是计时器会向前跳几秒钟。以下是代码段:
@Override
protected void onCreate(Bundle savedInstanceState) {
this.timerHandler = new Handler();
startButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!MainActivity.running && !MainActivity.paused) {
MainActivity.running = true;
MainActivity.paused = false;
MainActivity.startTime = System.currentTimeMillis();
startTimer();
startButton.setText("PAUSE");
}
else if (MainActivity.running && !MainActivity.paused) {
MainActivity.running = false;
stopTimer();
MainActivity.paused = true;
MainActivity.pauseTime = System.currentTimeMillis();
MainActivity.pauseTimerText = timerText(); // Eg: 00:00:08
startButton.setText("RESUME");
}
else if(MainActivity.paused) {
MainActivity.running = true;
MainActivity.paused = false;
startTimer();
startButton.setText("PAUSE");
}
resetButton.setVisibility(View.VISIBLE);
}
});
}
Runnable timerRunnable = new Runnable() {
@Override
public void run() {
if (!MainActivity.running) {
return;
}
if (pauseTimerText != null)
{
MainActivity.timerTV.setText(pauseTimerText); // this gets set to 00:00:08 here
pauseTimerText = null;
}
else
{
MainActivity.timerTV.setText(timerText());
}
timerHandler.postDelayed(timerRunnable, 100); // this changes the timer text.
}
};
void startTimer() {
MainActivity.running = true;
timerRunnable.run();
}
void stopTimer() {
MainActivity.running = false;
timerHandler.removeCallbacks(timerRunnable);
timerHandler.removeCallbacksAndMessages(null);
}
如果我的pauseTimerText是00:00:08,那么在runnable" MainActivity.timerTV.setText(pauseTimerText);" line确实将计时器文本设置为00:00:08,但我注意到在postDelayed执行后,而不是在UI上显示00:00:08的计时器,它会显示类似于00:00:13,即它也会加起来显示暂停的时间。
看起来postDelayed无法正常工作或者removeCallBacks没有删除所有内容。