我有一个测验应用程序sourcecode在 recyclerView 中有多个 radioGroup,我希望每次选择某个位置(radioGroup)中的正确 radioButton 时,它都应该更新分数 correct++
并将其发送到以下 Activity 。
@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();
}
}
}
}
关于java - 如何更新所选单选组/位置的每个单选按钮的分数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60813677/