我有一个基本的工作测验应用程序。我正在设置一个警告对话框,为用户提供问题说明(无论是对还是错)
问题:我无法理解,如何设置逻辑:在AlertDialog上暂停我的CountDownTimer,并在点击关闭对话框按钮后自动恢复它。
仅供参考:我已经找到了关于如何暂停和恢复CountDownTimer的答案,但我无法找到以编程方式为AlertDialog设置它的任何答案。
这是我的工作代码:
new CountDownTimer(40000, 1000) {
public void onTick(long millisUntilFinished) {
timer.setText("Sec: " + millisUntilFinished / 1000);
}
public void onFinish() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(EasyLevel1.this);
alertDialogBuilder
.setTitle("Time's Up!")
.setMessage("Your Final Score is " + mScore + " points.")
.setCancelable(false)
.setPositiveButton("REPLAY",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
startActivity(new Intent(getApplicationContext(), EasyLevel1.class));
finish();
}
})
.setNegativeButton("EXIT",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
finish();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}.start();
这是我的答案逻辑:
answer1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(answer1.getText() == mAnswer){
mScore+=5;
score.setText("Score: " + mScore);
updateQuestion(rand.nextInt(mQuestionsLength));
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(EasyLevel1.this, R.style.quizAlert);
alertDialogBuilder
.setTitle("Bingo! Your answer is Correct.\n" + "Score: +5")
.setMessage("Correct Answer: " + mExplanation)
.setCancelable(true)
.setPositiveButton("Close", null);
//startActivity(new Intent(getApplicationContext(),MainActivity.class));
//finish();
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
} else {
mScore-=2;
score.setText("Score: " + mScore);
updateQuestion(rand.nextInt(mQuestionsLength));
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(EasyLevel1.this, R.style.quizAlert);
alertDialogBuilder
.setTitle("Oops! Your answer is Wrong.\n" + "Score: -2")
.setMessage("Correct Answer: " + mExplanation)
.setCancelable(true)
.setPositiveButton("Close", null);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
});
答案 0 :(得分:1)
您知道如何暂停/重新启动计时器,但是您错过了将警报对话框关闭时执行的代码放在何处。
您已经有了使用setPositiveButton("Close", null)
执行此操作的基础。而不是null
,您将需要使用将重新启动计时器的侦听器。像这样:
alertDialogBuilder.setPositiveButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Do timer stuff.
}
});
有关详细信息,请参阅文档here。