java - 如何更新所选 radioGroup/位置的每个 radioButton 的分数?
问题描述
我在 recyclerView 中有一个带有多个 radioGroups 的测验应用程序源代码,我希望每次选择某个位置(radioGroup)的正确单选按钮时,它应该更新分数correct++
并将其发送到如下活动。
@Override
public void onClick(View view) {
boolean checked = ((RadioButton) view).isChecked();
if (checked) {
int radioButtonID = mRadioGroup.getCheckedRadioButtonId();
View radioButton = mRadioGroup.findViewById(radioButtonID);
int selectedAnswerIndex = mRadioGroup.indexOfChild(radioButton);
RadioButton r = (RadioButton) mRadioGroup.getChildAt(selectedAnswerIndex);
String selectedAnswer = r.getText().toString();
int position = getAdapterPosition();
Object object = mArrayList.get(position);
String correctAnswer = ((Quiz) object).mCorrectAnswer;
if (selectedAnswer.equals(correctAnswer)) {
correct++;
editor.putInt("score", correct);
editor.apply();
}
}
}
这仅适用于一个radioGroup,就像我从不同位置选择另一个radioButton 一样,分数correct
始终为1,可能是因为在onClick
再次执行函数之前它被重置为默认值。
我可能的解决方案是i <= arrayList.size()
包含一个循环,if (checked)
以防止分数correct
被重置为默认值 = 0,但我不知道将它放在哪里以及包含什么,因为用户不必从每个 radioGroup 中进行选择(除非最简单的情况是要求)。
如何更新所选 radioGroup/位置的每个 radioButton 的分数?
解决方案
添加for循环解决了一切
@Override
public void onClick(View view) {
boolean checked = ((RadioButton) view).isChecked();
int position = getAdapterPosition();
for (int i = 0; i <= position; i++) {
if (checked) {
int radioButtonID = mRadioGroup.getCheckedRadioButtonId();
View radioButton = mRadioGroup.findViewById(radioButtonID);
int selectedAnswerIndex = mRadioGroup.indexOfChild(radioButton);
RadioButton r = (RadioButton) mRadioGroup.getChildAt(selectedAnswerIndex);
String selectedAnswer = r.getText().toString();
Object object = mArrayList.get(position);
String correctAnswer = ((Quiz) object).mCorrectAnswer;
if (selectedAnswer.equals(correctAnswer)) {
correct++;
editor.putInt("score", correct);
editor.apply();
}
}
}
}
推荐阅读
- github - 上传到git时不小心删除了文件
- javascript - HTML 输入文本:隐藏字符而不删除它们
- excel - Excel自动填充超过76000行的列不起作用
- node.js - 如何制作更大的 CKeditor 的工具栏按钮?包含图片
- python - 将标签更改为 IOB 格式
- docker - Docker-compose 跳过 CMD 命令登录服务
- r - R - 按两个条件分组,如果所有值都为 0,则删除所有行,但如果不是 0,则保留
- nginx - Nginx 白名单域
- javascript - 带有SuccessHandler() 的 Google Apps 脚本无法按预期工作
- c - WM_MOUSEWHEEL 似乎不是_总是_生成的,是什么给出的?