我正在使用带有简单自定义适配器的 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;
}
我已经在 boolean 值的 ArrayList 中保留了复选框:已选中。
如有任何帮助,我们将不胜感激。
最佳答案
当您调用 holder.nameCheckBox.setChecked(checked.get(position));
来配置要为此 View 显示的 View 时,在标记仍然具有上一个复选框的位置。
在调用 setChecked
之前尝试删除监听器(将其设置为 null
)
关于java - Android 复选框 Listview 回收导致意外的框检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21919841/