//这个监听一定要放在checkbox初始化的方法之前,否则无效。是因为滑动的时侯会重新给checkbox赋值造成的。
holder.cbFileSel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.e("isChecked",isChecked+"---"+position);
checkedItems.put(position,isChecked);
}
});
holder.cbFileSel.setChecked(checkedItems.get(position));
集合初始化
private HashMap<Integer,Boolean> checkedItems;
public FileListAdapter(Context context, ArrayList<Files> datas, int layoutID) {
super(context, datas, layoutID);
checkedItems=new HashMap<>();
for(int i=0;i<datas.size();i++){
checkedItems.put(i,false);
}
}
方法二:利用arraylist解决
private List<Integer> checkPositionlist;
private ArrayList<Files> checkedFiles;
public PictureSelectorAdapter_1(ArrayList<Files> files, ArrayList<Files> checkedFiles) {
this.files = files;
checkPositionlist = new ArrayList<>();
this.checkedFiles = checkedFiles;
}
/**
* 解决checkbox的多选冲突
* @param holder
* @param position
* @param currentFile
*/
private void checkboxMulConflict(final MyViewHolder holder, final int position, final Files currentFile) {
holder.checkbox.setTag(new Integer(position));//防止复用导致的checkbox多选的问题。
//防止复选的辅助list
if (checkPositionlist != null) {
holder.checkbox.setChecked((checkPositionlist.contains(new Integer(position)) ? true : false));
} else {
holder.checkbox.setChecked(false);
}
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
if (!checkPositionlist.contains(holder.checkbox.getTag())) {
checkPositionlist.add(new Integer(position));
checkedFiles.add(currentFile);
}
} else {
if (checkPositionlist.contains(holder.checkbox.getTag())) {
checkPositionlist.remove(holder.checkbox.getTag());
checkedFiles.remove(currentFile);
}
}
}
});
}