我使用以下代码以 00:00 格式使用时间倒数计时器:
int timeCount = 150000;
public String formatTime(long millis) {
String output = "00:00";
long seconds = millis / 1000;
long minutes = seconds / 60;
seconds = seconds % 60;
minutes = minutes % 60;
String sec = String.valueOf(seconds);
String min = String.valueOf(minutes);
if (seconds < 10)
sec = "0" + seconds;
if (minutes < 10)
min= "0" + minutes;
output = min + " : " + sec;
return output;
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kviz);
brojacVremena.start();
}
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
public void onFinish() {
}
public void onTick(long millisUntilFinished) {
vreme.setText("" + millisUntilFinished / 1000);
}
}
MyCount brojacVremena = new MyCount(timeCount, 1000)
{
public void onTick(long millisUntilFinished)
{
vreme.setText("" + formatTime(millisUntilFinished));
}
public void onFinish()
{
finish();
}
};
这很好用。但是,当我的游戏结束时,我使用 startActivityForResult 启动一个弹出窗口,并且在用户按下 OK 按钮后,我开始下一个级别,我需要更新我的时间。它不再是 150000 毫秒,现在不同了。我这样做:
static final int MY_REQUEST2 = 1;
Intent i = new Intent(Kviz.this, Popup_nivoi.class);
numberOfQuestions = 13;
timeCount = 160000;
i.putExtra("time", 160);
startActivityForResult(i, MY_REQUEST2);
在这里,我用新值更新 int 变量 timeCount,但是当计时器启动时,我又从 150 秒开始。我究竟做错了什么?
此方法适用于我在此类中使用的少数其他变量,例如点、错误、尝试离开等。只有时间变量不会更新。