我正在为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;
}
}
};
按钮开始/停止的监听器:
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);
}
}
});
答案 0 :(得分:2)
解决方案是替换:
time = timer.getElapsedTime();
timeStoped = timeStoped + time;
使用:
time = timer.getElapsedTime() + timeStopped;
timeStopped = time;
答案 1 :(得分:0)
以小时:分钟:秒格式设置时间的更简单方法可能是:
Format formatter = new SimpleDateFormat("hh mm ss SSS");
String[] parsedTime = formatter.format(time).split(" ");
hours.setText(parsedTime[0]);
minutes.setText(parsedTime[1]);
seconds.setText(parsedTime[2]);
millis.setText(parsedTime[3]);
要在多次停止后保持准确的时间,您需要更改此信息:
time = timer.getElapsedTime();
timeStoped = timeStoped + time;
对于检查之前已过去time
的内容,可能是这样的:
time = timer.getElapsedTime() + time;
timeStoped = timeStoped + time;
这些与:
相同 time += timer.getElapsedTime();
timeStoped += time;