I am creating a quiz app.I have a running count down timer on Quiz activity. I want to show a dialogue /alert box in between. When the dialogue box is open the count down timer is stopped. But when dialogue box is closed count down timer fails to start again. please help.
here is my code
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'
}
});
I have already a countdown timer defined in onCreate as follows
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);
}
}
First you have to save CountDownTimer's milis into a variable because timer.cancel();
resets the timer. Then you create onClickListener for negative button in which you recreate the timer using saved 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();
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.