1. 程式人生 > >Recycleview checkbox 複用出現混亂解決方法

Recycleview checkbox 複用出現混亂解決方法

今天在做專案的一個我的收藏頁面時要實現這麼一個效果:
這裡寫圖片描述
每個item 前面都有一個checkbox ,主要佈局是recycleview 。當我們選中某項時,繼續往下滑動下面某個的checkbox也會變成選中狀態。
解決方法一比較暴力 viewHolder.setIsRecyclable(false);
這樣viewholder就不進行復用,也不存在checkbox 混亂選中的問題了,但是 你滑動的時候卡的要死。

第二種就是在獲取到的bean中設定一個標誌位,但是需要修改bean 。雖然只是加個欄位的問題,但是不建議。

第三種就是用個輔助list記錄選中的item. 這還不夠,還要配合viewholder的settag().

1.在繫結view的時候
viewHolder.checkBox.setTag(new Integer(position));//設定tag 否則劃回來時選中消失

    if (checkPositionlist != null) {
        ((MyViewHolder) holder).checkBox.setChecked((checkPositionlist.contains(new Integer(position)) ? true : false));
    } else {
        ((MyViewHolder) holder).checkBox.setChecked(false);
    }

2.選中監聽事件:

 viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                MyCollectionBaseBean baseBean = data.getFavoritesList().get(position);
if (isChecked) { //Log.e("fangchao 1", viewHolder.checkBox.getTag() + ""); if (!checkPositionlist.contains(viewHolder.checkBox.getTag())) {//這句要有 ,否則不復用了,但是你再滑動回去的時候,都成了為選中。這是因為你的item滑出可視範圍時,就會觸發oncheckchange事件,所以用第一步繫結的tag進行二次判斷。防止選中的丟失 checkeddata.add(baseBean); checkPositionlist.add(new Integer(position)); } } else { //Log.e("fangchao 2", viewHolder.checkBox.getTag() + ""); if (checkPositionlist.contains(viewHolder.checkBox.getTag()))//這句同上,二次判斷{ checkeddata.remove(baseBean); checkPositionlist.remove(new Integer(position)); } } } });

完整程式碼,自己摘著看:


/**
 * Created By Fangchao On 2015/3/5
 */
public class CollectionAdapter extends FooterAdapter {
    private MyCollectionListBean data;// 元資料
    private List<MyCollectionBaseBean> checkeddata = new ArrayList<>();// 選中的資料
    private ImageLoader mImageLoader;
    private List<Integer> checkPositionlist;

    public CollectionAdapter(MyCollectionListBean data) {
        this.data = data;
        mImageLoader = new ImageLoader(MyApplication.getInstance()
                .getRequestQueue(), BitmapCache.getInstance());
        checkPositionlist = new ArrayList<>();
    }


    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView txt_onsale, txt_mj, txt_present, goodsname, goods_describe;
        public TextView price, mark_price, commentsnums;
        CheckBox checkBox;
        NetworkImageView goods_img;
        public View v;

        public MyViewHolder(View v) {
            super(v);
            this.v = v;
            txt_onsale = (TextView) v.findViewById(R.id.txt_onsale);
            txt_mj = (TextView) v.findViewById(R.id.txt_mj);
            txt_present = (TextView) v.findViewById(R.id.txt_present);
            goods_describe = (TextView) v.findViewById(R.id.tv_production_describ);
            goodsname = (TextView) v.findViewById(R.id.tv_goods_name);
            price = (TextView) v.findViewById(R.id.tv_goods_price);
            mark_price = (TextView) v.findViewById(R.id.tv_goods_markprice);
            commentsnums = (TextView) v.findViewById(R.id.tv_goods_commentsnums);
            checkBox = (CheckBox) v.findViewById(R.id.collection_cb);
            goods_img = (NetworkImageView) v.findViewById(R.id.mycollection_item_image);

        }


    }

    @Override
    public boolean useFooter() {
        return true;
    }

    @Override
    public RecyclerView.ViewHolder onCreateContentItemViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_collection, parent, false);

        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindContentItemView(RecyclerView.ViewHolder holder, final int position) {
        MyViewHolder viewHolder = (MyViewHolder) holder;
        // viewHolder.setIsRecyclable(false);
        viewHolder.goodsname.setText(data.getFavoritesList().get(position).getGoods().getGoodsName());
        if (StringUtils.isBlank(data.getFavoritesList().get(position).getGoods().getGoodsSlogan())) {
            viewHolder.goods_describe.setVisibility(View.GONE);
        } else {
            viewHolder.goods_describe.setVisibility(View.VISIBLE);
            viewHolder.goods_describe.setText(data.getFavoritesList().get(position).getGoods().getGoodsSlogan());
        }
        viewHolder.price.setText(PriceTools.formatStr(data.getFavoritesList().get(position).getGoods().getShopPrice()));
        viewHolder.price.setTextColor(Color.parseColor("#E5004B"));
        viewHolder.mark_price.setText(PriceTools.formatStr(data.getFavoritesList().get(position).getGoods().getMarketPrice()));
        viewHolder.mark_price.setBackgroundResource(0);
        viewHolder.mark_price.getPaint().setFlags(
                Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG); // 設定中劃線並加清晰
        viewHolder.commentsnums.setText(data.getFavoritesList().get(position).getGoods().getCommentCount());
        viewHolder.checkBox.setTag(new Integer(position));//設定tag 否則劃回來時選中消失
        //checkbox  複用問題
        if (checkPositionlist != null) {
            ((MyViewHolder) holder).checkBox.setChecked((checkPositionlist.contains(new Integer(position)) ? true : false));
        } else {
            ((MyViewHolder) holder).checkBox.setChecked(false);
        }
        //Log.e("ffff",position+"");
        viewHolder.goods_img.setDefaultImageResId(R.drawable.item_default_img);
        viewHolder.goods_img.setErrorImageResId(R.drawable.item_default_img_err);
        viewHolder.goods_img.setImageUrl(data.getFavoritesList().get(position).getGoods().getImgFile(), mImageLoader);
        if (data.getFavoritesList().get(position).getGoods().getIsOnSale().equals("false")) {
            //下架
            viewHolder.price.setText("本商品已經下架");
            viewHolder.price.setTextColor(Color.GRAY);
            viewHolder.mark_price.setText("");
        } else if (data.getFavoritesList().get(position).getGoods().isIsNoStock()) {
            //缺貨
            viewHolder.mark_price.setBackgroundResource(R.drawable.ticket_is_outof_date_bg);
            viewHolder.mark_price.setText(" 缺貨 ");
            viewHolder.price.setTextColor(Color.GRAY);
            viewHolder.mark_price.getPaint().setFlags(0);
        }
        //cb 的選中事件
        onchecked(viewHolder, position);


    }

    private void onchecked(final MyViewHolder viewHolder, final int position) {

        viewHolder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                MyCollectionBaseBean baseBean = data.getFavoritesList().get(position);

                if (isChecked) {
                    //Log.e("fcccc 1", viewHolder.checkBox.getTag() + "");
                    if (!checkPositionlist.contains(viewHolder.checkBox.getTag())) {
                        checkeddata.add(baseBean);
                        checkPositionlist.add(new Integer(position));
                    }
                } else {
                    //Log.e("fcccc 2", viewHolder.checkBox.getTag() + "");
                    if (checkPositionlist.contains(viewHolder.checkBox.getTag())) {
                        checkeddata.remove(baseBean);
                        checkPositionlist.remove(new Integer(position));
                    }
                }
            }
        });
    }

    @Override
    public int getContentItemCount() {
        if (data != null)
            return data.getFavoritesList().size();
        else return 0;
    }

    @Override
    public int getContentItemType(int position) {
        return 0;
    }

    public void getdata(MycheckListener listener) {
        listener.getcheckeddata(checkeddata);
    }

    public interface MycheckListener {
        void getcheckeddata(List<MyCollectionBaseBean> listBean);
    }
}