【问题标题】:How to update the score for every radioButton of the radioGroup/position the selected?如何更新所选 radioGroup/位置的每个 radioButton 的分数?
【发布时间】:2020-03-23 12:34:37
【问题描述】:

我有一个测验应用程序sourcecode 在recyclerView 中有多个radioGroups,我希望每次选择某个位置(radioGroup)的正确radioButton 时,它应该更新分数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 的分数?

【问题讨论】:

    标签: java android radio-group


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-15
      • 2021-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-02-17
      • 2016-08-14
      • 1970-01-01
      相关资源
      最近更新 更多