设计图如下
由于Recyclerview的复用机制,RadioButton 选择会出现错误,实现的代码如下:主要是Adapter的实现(Adapter使用的BaseRecyclerViewAdapterHelper开源封装库),
public class ChineseMedicineAdapter extends BaseQuickAdapter<String,BaseViewHolder> {
//用来记录每个选项单选结果,记录的结果是这样的{0=1,1=3,2=4.....}
private SparseIntArray sia = new SparseIntArray();
/*
* 用于获取结果
* */
public SparseIntArray getSia() {
return sia;
}
public ChineseMedicineAdapter(int layoutResId) {
super(layoutResId);
}
@Override
protected void convert(@NotNull BaseViewHolder baseViewHolder, String s) {
RadioButton rb1 = baseViewHolder.getView(R.id.rb_1);
RadioButton rb2 = baseViewHolder.getView(R.id.rb_2);
RadioButton rb3 = baseViewHolder.getView(R.id.rb_3);
RadioButton rb4 = baseViewHolder.getView(R.id.rb_4);
RadioGroup rg = baseViewHolder.getView(R.id.item_rg);
rb1.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked){
sia.append(baseViewHolder.getAdapterPosition(),1);
}
});
rb2.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked){
sia.append(baseViewHolder.getAdapterPosition(),2);
}
});
rb3.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked){
sia.append(baseViewHolder.getAdapterPosition(),3);
}
});
rb4.setOnCheckedChangeListener((buttonView, isChecked) -> {
if (isChecked){
sia.append(baseViewHolder.getAdapterPosition(),4);
}
});
int i = sia.get(baseViewHolder.getAdapterPosition(),-1);
switch (i){
case 1:
rb1.setChecked(true);
break;
case 2:
rb2.setChecked(true);
break;
case 3:
rb3.setChecked(true);
break;
case 4:
rb4.setChecked(true);
break;
case -1:
rg.clearCheck();
break;
default:
break;
}
}
}
最后遍历SparseIntArray 即可
SparseIntArray sia = medicineAdapter.getSia();
if (sia.size() < 30){
//
ToastUtils.showLong("请完成所有题目");
return;
}
for (int i = 0; i < sia.size(); i++) {
int key = sia.keyAt(i);
int value = sia.get(key);
}