RecyclerView条目复用导致混乱的解决方案之一

  无论Recycler或者ListView都采用复用机制这是两个控件的精华所在,但是这个复用机制在某些特定的情况总会给我们带来不必须要的烦恼,我模拟一下RecyclerView的复用,条目上的控件只用TextView和CheckBox,我们先来看下Item的XML文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/item_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:text="测试一下"
        android:textColor="@android:color/holo_blue_light"
        android:textSize="14sp" />

    <CheckBox
        android:id="@+id/item_cb"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="50dp" />

</LinearLayout>


下面展示一下复用的情况和代码

明显看到条目被复用了,关于条目复用解决方案查了下大致分为两种,一种通过Map集合管理View和Position,一种是通过集合存储当前的点击状态,关于第一种方案,做过测试,绕过了复用机制,数据量小的情况下可以使用,但是数据量过大内存开销很大,有兴趣的朋友可以尝试下,本文主要说第二种方案,在保留复用机制的前提下,解决复用!直接关键处代码


holder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                if (b) {                   
                    if (!l.contains(position)) {
                         l.add(position);                     
                    }
                } else {                  
                    if (l.contains(position)) {
                        int i = l.indexOf(position);
                        l.remove(i);
                      
                    }
                }
            }
        });

       holder.cb.setChecked(l.contains(position) ? true : false);//还原状态





  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值