androidandroid-recyclerviewradio-buttonradio-groupmultiple-choice

RadioButtons auto checked on RecyclerView scrolling without clicking


I am developing a model test app where each test has 20 questions and each questions has 4 radio button options inside a radio group.

Now while scrolling and selecting radio button, I have encountered automatic radio button checks.

I want to know why this problem is occurring and the solution. Here is my RecylerView sample code. `

@Override
public void onBindViewHolder(@NonNull QuizQuestionViewHolder holder, int position) {

    final QuestionsWithOption questionsWithOption = questionsWithOptionList.get(position);
    final List<Option> optionList = questionsWithOption.getOptions();

    holder.quizQuestionTextView.setText(questionsWithOption.getTitle());

    if (holder.quizOptionsRadioGroup.getChildCount() == 0) {
        addRadioButtons(holder.quizOptionsRadioGroup, optionList,
                questionsWithOption.getId());
    }
}

private void addRadioButtons(RadioGroup quizOptionsRadioGroup,
                             List<Option> optionList, final int questionId) {

    final RadioButton[] radioButtons = new RadioButton[optionList.size()];

    for(int i = 0; i < optionList.size(); i++){
        radioButtons[i] = new RadioButton(context);
        radioButtons[i].setText(optionList.get(i).getName());
        radioButtons[i].setTextSize(14);
        radioButtons[i].setId(optionList.get(i).getId());
        radioButtons[i].setTag(optionList.get(i));
        radioButtons[i].setPadding(8, 8, 8, 8);

        quizOptionsRadioGroup.addView(radioButtons[i]);
    }

    quizOptionsRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton checkedRadioButton = group.findViewById(checkedId);

            Option quizOptions = (Option) checkedRadioButton.getTag();

            Log.d("Checked", quizOptions.getName());
        }
    });
}

This is the screenshot of my app. These radio buttons checks automatically after scrolling. I have not touched any button.

`This is the screenshot of my app. These radio buttons checks automatically after scrolling. I have not touched any button.


Solution

  • Well this is something interesting about recyclerview. The onBindView function is called again and again as a recycler.So when you change checked status for radio buttons other views radio buttons also gets changed as they take advantage of the reference.

    The solution is to always check necessary conditions for checking and unchecking the radio buttons at onBindView function