Selecting one RadioButton value and scrolling back removing the selected one in RecyclerView

后端 未结 9 1901
温柔的废话
温柔的废话 2020-12-15 18:24

In my application am displaying 20 multiple choice questions with the help of RecyclerView.

If I change the value of first RadioGroup and s

9条回答
  •  一个人的身影
    2020-12-15 18:54

    The problem is that the recycler view is recycling (like the name says) your views.

    The system creates a certain amount of ViewHolders to fill your screen after reaching that amount it reuses the already existent ViewHolders.

    If you set the button checked in your first listentry and it reuses the ViewHolder for your 7th listentry the button is still checked(because it got set in the ViewHolder).

    To fix this problem you need to set the default appearance for your listentries in onBindViewHOlder every time.

    Update:

    public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
    
        final Student student = stList.get(position);
    
        viewHolder.tvQuestionNumber.setText(student.getQuestionNumber());
    
        viewHolder.tvQuestion.setText(student.getQuestion());
    
        viewHolder.rbAns1.setText(student.getAnswer1());
    
        viewHolder.rbAns2.setText(student.getAnswer2());
    
        viewHolder.rbAns3.setText(student.getAnswer3());
    
        viewHolder.rbAns4.setText(student.getAnswer4());
    
        viewHolder.rbAns5.setText(student.getAnswer4());
    
        viewHolder.rgAnswers.clearCheck();
    
        viewHolder.rgAnswers.check(student.getSelectedRadioButtonId());
    
        viewHolder.rgAnswers.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                student.setSelectedRadioButtonId(checkedId);
                Log.v("hello"+position,checkedId+"");
            }
        });
    }
    

    I slightly updated your new approach, maybe this helps ?

提交回复
热议问题