我正在尝试实现一个自定义数组适配器,它必须用一个文本和一个复选框来可视化一个列表视图。我需要记住选择,并且我希望每次选中一个选项时,所有其他选项都作为单选按钮未选中。
这是我的代码
public class RAnswerAdapter extends ArrayAdapter<RAnswer> {
private final ArrayList<RAnswer> list;
private final Activity context;
public RAnswerAdapter(Activity context, ArrayList<RAnswer> list) {
super(context, R.layout.answer_item, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.answer_item_radio, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.answerName);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.checkAnsw);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Answer element = (Answer) viewHolder.checkbox.getTag();
for(Answer a: list)
//if true
if(a.isSelected())
//I set at false
a.setSelected(false);
//I set the new at true
element.setSelected(buttonView.isChecked());
//I refresh the list
notifyDataSetChanged();
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.text.setText(list.get(position).getAnswer_option());
holder.checkbox.setChecked(list.get(position).isSelected());
return view;
}
}
代码实际上以一种奇怪的方式工作......列表的前 4 个元素工作完美,其他所有元素都无法检查!为什么这个?错误在哪里?
谢谢您的帮助