解决listView或者recycleView 的item有CheckBox复用问题

步骤1:自定义一个接口,接口中申明一个方法

public interface ProductLabelListener {

    void childDelete(int Position);//这是删除
    void change(boolean b,int position);//b是checkbox的状态,position是当前item在数据源中的位置。
}

步骤2:让listView或者recycleView所在的Activity去实现这个接口,实现里面的方法

步骤3:在adapter中写一个方法进行接口对象的设置

public void setmListener(ProductLabelListener mListener) {
    this.mListener = mListener;
}

private ProductLabelListener mListener;

步骤4:在listView或者recycleView所在的Activity调用setmListener()方法去设置接口对象

步骤5:在adapter中设置CheckBox监听事件,调用定义好的接口中的方法

holder.cb_is_print.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        mListener.change(isChecked,position);
    }
});

步骤6:在listView或者recycleView所在的Activity中的change()方法中设置CheckBox的状态

    @Override
    public void change(boolean b, int position) {
        label_data.get(position).setChecked(b);//设置list中对应的item的CheckBox的状态
//        adapter.setData(label_data);
        calculate();//进行数据改变操作
    }

附加:listview的item实现斑马条纹效果

/**
 * 显示斑马条纹样式
 */
if (position % 2 == 0) {
    holder.ll_container.setBackgroundColor(mContext.getResources().getColor(R.color.colorWhite));
} else {
    holder.ll_container.setBackgroundColor(mContext.getResources().getColor(R.color.colorTextHint));
}
ll_container 是listview的item的最外层布局,可以是LinearLayout等等


猜你喜欢

转载自blog.csdn.net/freak_csh/article/details/79556599