Android Studio中CountDownTimer异常问题排查与修复求助
修复CountDownTimer倒计时不更新与题目切换异常问题
我帮你排查出两个核心问题,修改后就能完全解决你的需求:
1. 倒计时文本停滞的根本原因
你的startTimer()方法里犯了两个关键错误:
- 总时长设置为12000毫秒(12秒),但你要的是10秒倒计时;
onTick里的条件判断完全写错了——millisUntilFinished是毫秒单位,初始值12000远大于10,导致倒计时文本永远不会更新,一直停留在初始的"10"。
修改后的startTimer()应该是这样:
private void startTimer() { countDown = new CountDownTimer(10000, 1000) { // 总时长改为10秒 @Override public void onTick(long millisUntilFinished) { // 直接计算剩余秒数并更新文本,去掉错误的条件判断 timer.setText(String.valueOf(millisUntilFinished / 1000)); } @Override public void onFinish() { changeQuestion(); } }; countDown.start(); }
2. 额外优化:自动切换题目时重置按钮状态
虽然这不是你当前的核心问题,但倒计时结束自动切题后,上一题的按钮红/绿状态不会重置,会影响体验。你可以在changeQuestion()里添加重置逻辑:
private void changeQuestion() { if (quesNum < questionList.size() - 1) { quesNum++; // 重置所有选项按钮的背景色 option1.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#e8c1e1"))); option2.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#e8c1e1"))); option3.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#e8c1e1"))); option4.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor("#e8c1e1"))); playAnim(question, 0, 0); playAnim(option1, 0, 1); playAnim(option2, 0, 2); playAnim(option3, 0, 3); playAnim(option4, 0, 4); qCount.setText(String.valueOf(quesNum + 1) + "/" + String.valueOf(questionList.size())); timer.setText(String.valueOf(10)); startTimer(); } else { //Go to Score Activity Intent intent = new Intent(QuestionActivity.this, ScoreActivity.class); intent.putExtra("SCORE",String.valueOf(score) + "/" + String.valueOf(questionList.size())); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK); startActivity(intent); QuestionActivity.this.finish(); } }
关于"约5秒后题目切换"的错觉
之前你设置的总时长是12秒,但因为倒计时文本没更新,你可能误以为时间过得更快。修改后倒计时会准确从10倒数到0,时间到后自动切换题目,完全符合你的预期。
内容的提问来源于stack exchange,提问作者user14769698
相关产品推荐
相关产品推荐

