I have created a radio group in recycler view, and implemented onCheckedChangeListener which should work fine.
But for some reasons, after first selection whenever i scroll the recycler view this onCheckedChangeListener gets triggered even though i didn't select any option of radio group.
Here is the code for checked change
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
final MyViewHolder holder = (MyViewHolder) viewHolder;
final String id = studentNames.get(position).getStudent_id();
final String name = studentNames.get(position).getStudent_name();
holder.id.setText(id);
holder.name.setText(name);
holder.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
if (radioGroup.isPressed()){ // from one of the links on stackoverflow
switch (checkedId) {
case R.id.present:
calculatedAttendance.add(new Attendance(holder.id.getText().toString(), holder.name.getText().toString(), context.getString(R.string.present)));
break;
case R.id.absent:
calculatedAttendance.add(new Attendance(holder.id.getText().toString(), holder.name.getText().toString(), context.getString(R.string.absent)));
break;
case R.id.leave:
calculatedAttendance.add(new Attendance(holder.id.getText().toString(), holder.name.getText().toString(), context.getString(R.string.leave)));
break;
}
}
}
});
}
}
I added breakpoints in android studio and found out that this onCheckedChange is getting fired even when no option is selected of that radio group.
A related question might have been asked before but they all address Compound Button or CheckBox, I am asking about radio buttons.
PS: I did tried answers from this link onCheckedChanged called automatically
And thats the reason why you see taht radioGroup.isPressed check at the starting
I even used it like this:
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
RadioButton button= (RadioButton) radioGroup.findViewById(checkedId);
//both getLayoutPosition and getAdapterPosition
final String id = studentNames.get(getLayoutPosition()).getStudent_id();
final String name = studentNames.get(getLayoutPosition()).getStudent_name();
switch (checkedId) {
case R.id.present:
if(button.isPressed()){
calculatedAttendance.add(new Attendance(id, name, context.getString(R.string.present)));
}
break;
case R.id.absent:
if(button.isPressed()) {
calculatedAttendance.add(new Attendance(id , name, context.getString(R.string.absent)));
}
break;
case R.id.leave:
if(button.isPressed()){
calculatedAttendance.add(new Attendance(id, name, context.getString(R.string.leave)));
}
break;
}
}
Nothing seems to work