RecyclerView 复用产生的数据混乱竟然是ConstraintLayout导致的?

首先,来看问题

正常的item中都会有页号,但是来回翻页发现会有item中不显示页号

作为资深码农,肯定了这是RecyclerView复用itemView导致的混乱,于是首先对代码检查,发现有if 的地方必有else, 本身的代码并不能导致bug的产生,如下图:

接着在pageNum.text前后均打了日志,输出了TextView的text、visible,发现一切正常!

陷入坑中了。。。

控件是visible的,是有内容的,那还有什么原因导致无法显示页号呢?

于是pageNum新增输出控件宽度,当看到日志结果,瞬间看到了曙光。

发现同一个itemView对象,pageNum的宽度会发生变化,当宽度有0、38、140。

检查布局,发现pageNum在ConstraintLayout下,layout_width = 0dp,靠左靠顶显示。因为ConstraintLayout的特性,当设置了控件的对齐方式会影响到控件的宽高,所以可以正常显示,但在itemView中涉及到了复用就产生了问题。根据日志来看是RecyclerView在显示当前页时会预载更多的数据,所以显示和预载时计算pageNum控件的宽度是不一样的,当复用时因为控件宽度已定,就造成了部分item不显示页号。

 <androidx.constraintlayout.widget.ConstraintLayout
        android:id="@+id/clItemBView"
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_80"
        android:layout_marginLeft="@dimen/dp_5"
        android:layout_marginRight="@dimen/dp_5"
        android:layout_marginBottom="@dimen/dp_5"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/iv_cover">
     
        <TextView
            android:id="@+id/pageNum"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/dp_10"
            android:ellipsize="end"
            android:maxLines="1"
            android:singleLine="true"
            android:text="P1"
            android:textColor="@color/c_3"
            android:textSize="@dimen/sp_21"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>

 解决方法:

android:layout_width="0dp" 改为 android:layout_width="wrap_content"

总结:在使用RecyclerView时产生了数据混乱,如果检查不出是哪里的问题时,看下是否使用了ConstraintLayout,因为使用不当也会导致数据混乱。

--------------------------------------------------------------------------------------------------------------------

在解决该问题时也发现别人也遇到了ConstraintLayout导致的复用数据混乱,附上地址

https://lishide.github.io/2018/05/30/Android-fix-rv-item-view-overlap/

 


版权声明:本文为qq_28868857原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。