我想为我的干预模型创建适配器。 项目将有两个带复选框的文本视图。干预模型只有许多String字段。 我的适配器扩展了Basedapter:
public class CBAdapter extends BaseAdapter {
private LinkedList<Intervention> mData;
private Context mContext;
public CBAdapter(Context context, LinkedList<Intervention> data) {
mContext = context;
this.mData = data;
}
static class ViewHolder {
TextView tvTopText;
TextView tvLowText;
CheckBox checkbox;
}
@Override
public int getCount() {
return mData.size();
}
@Override
public Intervention getItem(int position) {
return mData.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.intervention_select_item,
null);
viewHolder.tvTopText = (TextView) convertView.findViewById(R.id.tvTopText);
viewHolder.tvLowText = (TextView) convertView.findViewById(R.id.tvBotText);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cbInterCheck);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final int pos = position;
viewHolder.tvTopText.setText(mData.get(position).getName());
viewHolder.tvLowText.setText(mData.get(position).getGlobalInterId());
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mData.get(pos).setSelected(isChecked);
}
});
return convertView;
}
public void setData(LinkedList<Intervention> data) {
this.mData = data;
this.notifyDataSetChanged();
}
}
但是当我点击时,例如,第三项,它将检查3和13项。 什么问题?以及如何使用复选框创建适配器? :(
答案 0 :(得分:2)
您没有正确实施“convertView”回收。此行不会引发错误,但不正确:
viewHolder = (ViewHolder) convertView.getTag();
“getTag”返回类型“Object”,因此它会进行转换,但它不是您想要的。它应该是:
viewHolder = (ViewHolder) convertView;
然后你的观点应该都有自己的CheckBox。