我有 Vraag 类,用于制作列表中的不同项目。该类有一个 Antwoord 类的数组。对于每个 Antwoord,我想要一个使用 for 循环添加的切换按钮。现在的问题是,当我在列表中滚动时,它会向列表项添加额外的切换按钮。这是我的适配器代码:
public class VraagListAdapter extends ArrayAdapter<Vraag>{
public Context context;
public List<Vraag> vragen;
ViewHolder holder;
int id = 0;
public VraagListAdapter(Activity context, List<Vraag> vragen){
super(context, R.layout.vraag_item, vragen);
this.context = context;
this.vragen = vragen;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.vraag_item, null, false);
holder = new ViewHolder();
holder.vraag = (TextView)convertView.findViewById(R.id.tv_vraag);
holder.group = (RadioGroup)convertView.findViewById(R.id.toggleGroup);
holder.position = position;
holder.toggle = new ToggleButton(context);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.vraag.setText(vragen.get(position).getVraag());
final int positievraag = position;
holder.group.setOnCheckedChangeListener(ToggleListener);
for(Antwoord a : vragen.get(position).getAntwoorden()){
holder.toggle = new ToggleButton(context);
holder.toggle.setText(a.getAntwoord());
holder.toggle.setTextOn(a.getAntwoord());
holder.toggle.setTextOff(a.getAntwoord());
holder.toggle.setId(id);
if(a.getVisible() == false){
holder.toggle.setVisibility(ToggleButton.INVISIBLE);
}
holder.toggle.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View view)
{
// your click actions go here
((RadioGroup)view.getParent()).check(view.getId());
vragen.get(positievraag).setAntwoord((String)holder.toggle.getText());
}
});
id++;
holder.group.addView(holder.toggle);
}
return convertView;
}
static class ViewHolder {
TextView vraag;
RadioGroup group;
ToggleButton toggle;
int position;
}
static final RadioGroup.OnCheckedChangeListener ToggleListener = new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(final RadioGroup radioGroup, final int i) {
for (int j = 0; j < radioGroup.getChildCount(); j++) {
final ToggleButton view = (ToggleButton) radioGroup.getChildAt(j);
view.setChecked(view.getId() == i);
}
}
};
}