我正在创建测验应用程序。我在测验活动中有一个倒计时计时器。我想在两者之间显示一个对话框/警报框。打开对话框时,倒数计时器将停止。但是当对话框关闭时,倒数计时器无法再次启动。请帮忙。
这是我的代码
btnHint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();// working fine
final AlertDialog.Builder dialog = new AlertDialog.Builder(QuizActivity.this);
dialog.setTitle("Read Carefully");
dialog.setMessage(c.getString(7));
dialog.setNegativeButton("Exit Hint", null);
dialog.show();
//how to start TIMER again after clicking 'Exit Hint'
}
});
我已经在onCreate中定义了一个倒数计时器,如下所示:
timer = new CountDownTimer(90000, 1000) {
@Override
public void onTick(long millisUntilFinished) {
String time = String.valueOf(millisUntilFinished / 1000);
tvClock.setText("Time" + "\n" + time + "/90");
int seconds = (int) (millisUntilFinished / 1000);
if (seconds >= 31) {
tvClock.setBackgroundResource(R.drawable.boxgreen);
} else if (seconds >= 16) {
tvClock.setBackgroundResource(R.drawable.boxyellow);
} else {
tvClock.setBackgroundResource(R.drawable.boxred);
}
}
答案 0 :(得分:0)
首先,您必须将CountDownTimer的milis保存到变量中,因为timer.cancel();
会重置计时器。然后,为否定按钮创建onClickListener,在其中使用保存的milis重新创建计时器。
CountDownTimer timer = new CountDownTimer(10000, 10) { //timer will count down 10 seconds and save time every 10ms
@Override
public void onTick(long millisUntilFinished) {
milis = millisUntilFinished;
//save time into field milis
//Update your view with progress here
}
@Override
public void onFinish() {
}
};
timer.start();
btnHint.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
timer.cancel();// working fine
final AlertDialog.Builder dialog = new AlertDialog.Builder(QuizActivity.this);
dialog.setTitle("Read Carefully");
dialog.setMessage(c.getString(7));
dialog.setNegativeButton("Exit Hint", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
timer = new CountDownTimer(milis, 10) {
@Override
public void onTick(long millisUntilFinished) {
milis = millisUntilFinished;
//save time again if you want to pause it again
//Update your view with progress here
}
@Override
public void onFinish() {
}
};
timer.start();
}
});
dialog.show();
}
});