RecyclerView ViewHolder 中的 ConstraintLayout 性能

Performance of ConstraintLayout inside RecyclerView ViewHolder

在过去的 2 天里,我一直在尝试对为什么我的 RecyclerView 在滚动时如此慢得令人无法忍受进行分类,我已经将其缩小到我用于行的 ConstraintLayout。在 android 上使用 GPU 分析器显示 green/blueish 一直到屏幕顶部的绿色条,表明存在严重卡顿。很明显哪里出了问题。

这是我的取景器的样子:

class MyViewHolder(

    override val containerView: View) : RecyclerView.ViewHolder(containerView), LayoutContainer {
        fun bindTo(item: Item?, clickListener: (Item?) -> Unit) {
            text_item_name.text = item?.name
            Glide.with(containerView.context).load(item?.url).into(image_item)

            containerView.setOnClickListener { clickListener(item) }
        }
    }

这是我的布局。尽可能简单:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/selectableItemBackground"
    android:paddingBottom="@dimen/padding"
    android:paddingEnd="@dimen/padding_2x"
    android:paddingStart="@dimen/padding_2x"
    android:paddingTop="@dimen/padding">

    <ImageView
        android:id="@+id/image_item"
        android:layout_width="24dp"
        android:layout_height="24dp"
        android:layout_marginEnd="@dimen/margin_2x"
        android:layout_marginStart="@dimen/margin_2x"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/text_coin_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="@dimen/margin_2x"
        android:layout_marginStart="@dimen/margin_2x"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toEndOf="@id/image_item"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

所以我的问题是:我的布局有什么问题导致卡顿?我使用的 LayoutManager 不正确吗?约束是否导致透支?

如果我完全重写布局 XML 以基于 LinearLayout,它会像丝绸一样光滑。

嗯,终于找到罪魁祸首了:

android:layout_height="wrap_content"

如果我为此属性指定固定大小,一切都很好。确定每一行的视图高度的持续计算可能会导致问题。