ListView嵌套CheckBox滑动时CheckBox选中状态错乱

ListView嵌套CheckBox滑动时CheckBox选中状态错乱

代码

package com.example.check_listview;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by xiaoyehai on 2017/12/30/030.
 */

public class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {

    private Context mContext;
    private List mList;
    private int LayoutID;

    //存放已经选中的多选框
    private List checkedList = new ArrayList<>();

    public MyAdapter(Context context, List list, int layoutID) {
        mContext = context;
        mList = list;
        LayoutID = layoutID;
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = View.inflate(mContext, LayoutID, null);
            holder = new ViewHolder(convertView);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.checkBox.setTag(holder.checkBox.getId(), position);
        holder.checkBox.setOnCheckedChangeListener(this);
        //把已经在集合中多选框的设置为选中
        holder.checkBox.setChecked(checkedList.contains(position + ""));

        holder.tv.setText(mList.get(position));
        return convertView;
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        int position = (int) buttonView.getTag(buttonView.getId());
        //选中并且里面不包含当前位置
        if (isChecked && !checkedList.contains(position + "")) {
            checkedList.add(position + "");
        } else {
            checkedList.remove(position + "");
        }
    }

    static class ViewHolder {
        private CheckBox checkBox;
        private TextView tv;

        public ViewHolder(View convertView) {
            checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
            tv = (TextView) convertView.findViewById(R.id.tv);
        }
    }
}

ListView嵌套CheckBox滑动时CheckBox选中状态错乱_第1张图片

你可能感兴趣的:(android)