我正在使用带有简单自定义适配器的ListView开发应用程序,每行包含一个CheckBox对象。但是,由于ListView的回收功能(我不打算关闭),因此选中任何一个框时,也会同时检查ListView中上方或下方的其他框。
以下是我在适配器中的getView()以及自定义ViewHolder类:
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.populate_friends_row, null);
holder = new ViewHolder();
holder.nameCheckBox = (CheckBox) convertView.findViewById(R.id.isFriend);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.nameCheckBox.setText(data.get(position).contactLabel);
holder.nameCheckBox.setChecked(checked.get(position));
holder.nameCheckBox.setTag(String.valueOf(position)); // to properly track the actual position
holder.nameCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
int pos = Integer.parseInt(buttonView.getTag().toString());
checked.set(pos, isChecked);
}
});
return convertView;
}
public static class ViewHolder {
public CheckBox nameCheckBox;
}
我已经在ArrayList of booleans中选中了复选框:已选中。
任何帮助,将不胜感激,谢谢。
最佳答案
当您调用holder.nameCheckBox.setChecked(checked.get(position));
以配置要为此视图显示的视图时,将在标签仍具有上一个复选框的位置的同时调用侦听器。
尝试在调用null
之前删除侦听器(将其设置为setChecked
)。