首页 > 解决方案 > 如何更新所选 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 的分数?

标签: javaandroidradio-group

解决方案


添加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();
                    }
                }
            }
        }

推荐阅读