ListView复用导致checkBox错乱的解决方法


1. 采用SparseArray 和 View.settag();

    private SparseArray Cb_state = new SparseArray<>();//成员变量
    ----------------------------------------------关键代码getView中
    viewHolder.cb.setTag(R.id.cb,position);
    Boolean state = Cb_state.get(position,false);
    viewHolder.cb.setChecked(bean.getState());
    viewHolder.cb.setOnCheckedChangeListener(this)

监听:

    @Override
    public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) 
    {
        int posotion = (int) buttonView.getTag(R.id.cb);
        Cb_state.put(posotion,isChecked);
    }

2 在javaBean中增加一个boolean型的变量

        public class JavaBean {
        private boolean state;
        .........
        public void setState(boolean state) {
            this.state = state;
        }
         public boolean getState() {
            return state;
        }
       }

在getView中

 viewHolder.cb.setChecked(bean.getState());
 viewHolder.cb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bean.setState(true);
            }
        });

你可能感兴趣的:(android遇到的错误集)