Android Quiz应用倒计时异常:返回RecyclerView后自动启动后续答题页
解决RecyclerView返回后答题Activity自动启动的问题
嘿,我看了你的代码,马上就找到问题的根源了,咱们一步步来解决:
问题出在哪?
- 倒计时没在Activity销毁时停止:当你从答题页面按返回键回到RecyclerView时,那个答题Activity的
CountDownTimer还在后台偷偷跑着!等倒计时结束,它就会自动触发跳转下一题的逻辑,新打开的答题页又会启动自己的倒计时,这样连锁反应就导致剩下4个页面挨个自动打开了。 - Intent设置了错误的参数:你跳转时加了
Intent.CATEGORY_HOME(这是用来跳桌面的)和FLAG_ACTIVITY_NEW_TASK(会创建新的任务栈),这俩设置完全没必要,反而把正常的返回栈搞乱了,加剧了问题。
具体修复步骤
1. 给每个答题Activity加生命周期回调,停止倒计时
所有带倒计时的答题Activity(比如first_five_Questions_questions_1、first_five_Questions_questions_2等)都要加这段代码,确保页面销毁或暂停时,倒计时立刻停止:
@Override protected void onDestroy() { super.onDestroy(); // 销毁页面时取消倒计时,防止后台触发跳转 if (myCount != null) { myCount.cancel(); } } @Override protected void onPause() { super.onPause(); // 可选:如果希望切出页面就停止倒计时,也可以在这里取消 if (myCount != null) { myCount.cancel(); } }
2. 移除Intent里的错误设置
跳转时的这两行代码完全没用,删掉它们,让页面在默认的任务栈里运行:
原代码片段:
intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
修改后跳转代码:
Intent intent = new Intent(first_five_Questions_questions_1.this, first_five_Questions_questions_2.class); intent.putExtra("key", val); startActivity(intent); finish();
3. 优化按钮点击时的倒计时取消逻辑
为了避免空指针异常,点击按钮取消倒计时前先判断一下myCount是否为空:
@Override public void onClick(View v) { int selectedId = radioGroup.getCheckedRadioButtonId(); // 先判断倒计时实例是否存在再取消 if (myCount != null) { myCount.cancel(); } // 后续的单选判断和跳转逻辑不变 radioButton = (RadioButton) findViewById(selectedId); if(selectedId==R.id.Rd_btn_three__first_five_questions_q1) { val++; Intent intent = new Intent(first_five_Questions_questions_1.this, first_five_Questions_questions_2.class); intent.putExtra("key", val); startActivity(intent); finish(); } else { Intent intent = new Intent(first_five_Questions_questions_1.this, first_five_Questions_questions_2.class); intent.putExtra("key", val); startActivity(intent); finish(); } }
4. 确认RecyclerView的跳转逻辑
你的CustomRecyclerAdapterTests里启动答题Activity的代码是正常的,不需要修改,但要确保没有额外加奇怪的Intent Flags,保持当前逻辑就好。
做完这些修改,再测试一下:从RecyclerView进入答题页,按返回键回到列表,就不会再出现后续页面自动启动的问题了,跳转和返回的逻辑也会恢复正常。
内容的提问来源于stack exchange,提问作者jassim
相关产品推荐
相关产品推荐

