我正在使用带有简单自定义适配器的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;
}
我已经在布尔数组列表中持有复选框:选中。
任何帮助将不胜感激,谢谢。
当您调用holder.nameCheckBox.setChecked(checked.get(position));
来配置要为此视图显示的视图时,将调用侦听器,而标记仍具有上一个复选框的位置。
在调用setChecked
之前,请尝试删除侦听器(将其设置为 null
)