我正在为 Android 制作秒表应用程序。我想要单击停止时停止的时间,以及再次单击开始时要恢复的时间。我正在使用http://www.goldb.org/stopwatchjava.html类。目前,单击“开始”按钮会恢复时间,但是当我第二次单击“停止”时,它会显示错误的时间。再次在开始按钮上,时间正确恢复。这是我的代码:
Handler mHandler = new Handler()
{
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case MSG_START_TIMER:
timer.start(); //start timer
mHandler.sendEmptyMessage(MSG_UPDATE_TIMER);
break;
case MSG_UPDATE_TIMER:
time = timer.getElapsedTime() + timeStoped;
hh = time / 3600000;
hours.setText("" + formatter.format(hh));
time = time - hh * 3600000;
mm = time / 60000;
minutes.setText("" + formatter.format(mm));
time = time - mm * 60000;
ss = time / 1000;
seconds.setText("" + formatter.format(ss));
time = time - ss * 1000;
millis.setText("" + formatter.format(time / 10));
mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER,REFRESH_RATE); //text view is updated every second,
break;
//though the timer is still running
case MSG_STOP_TIMER:
mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates.
timer.stop();//stop timer
time = timer.getElapsedTime();
timeStoped = timeStoped + time;
hh = time / 3600000;
hours.setText("" + formatter.format(hh));
time = time - hh * 3600000;
mm = time / 60000;
minutes.setText("" + formatter.format(mm));
time = time - mm * 60000;
ss = time / 1000;
seconds.setText("" + formatter.format(ss));
time = time - ss * 1000;
millis.setText("" + formatter.format(time / 10));
break;
default:
break;
}
}
};
按钮 Start/Stop 的监听器:
startBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (!startIsPressed) {
mHandler.sendEmptyMessage(MSG_START_TIMER);
startIsPressed = true;
startBtn.setText(R.string.stop);
} else {
startIsPressed = false;
startBtn.setText(R.string.start);
mHandler.sendEmptyMessage(MSG_STOP_TIMER);
}
}
});