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

来源:互联网 发布:2016最近网络最火的dj 编辑:程序博客网 时间:2024/05/26 02:22
  无论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);//还原状态



1 1