【发布时间】:2019-01-29 06:33:14
【问题描述】:
我在回收站视图中创建了一个无线电组,并实现了 onCheckedChangeListener,它应该可以正常工作。
但由于某些原因,在第一次选择后,每当我滚动回收器视图时,即使我没有选择单选组的任何选项,也会触发 onCheckedChangeListener。
这是检查更改的代码
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;
}
}
}
});
}
}
我在 android studio 中添加了断点,发现即使没有选择该无线电组的选项,这个 onCheckedChange 也会被触发。
之前可能已经问过一个相关问题,但它们都涉及复合按钮或复选框,我问的是单选按钮。
PS:我确实尝试过此链接onCheckedChanged called automatically的答案
这就是为什么您在开始时看到 taht radioGroup.isPressed 检查的原因
我什至这样使用它:
@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;
}
}
似乎没有任何效果
【问题讨论】:
标签: android android-recyclerview radio-group