【问题标题】:Performance of ConstraintLayout inside RecyclerView ViewHolderRecyclerView ViewHolder内部ConstraintLayout的性能
【发布时间】:2019-01-07 07:54:34
【问题描述】:

在过去的 2 天里,我一直在尝试对我的 RecyclerView 为何在滚动时如此缓慢的原因进行分类,并且我已将其范围缩小到用于行的 ConstraintLayout。在 android 上使用 GPU 分析器会显示一直到屏幕顶部的绿色/蓝绿色条,表明存在大量卡顿。很明显出了点问题。

这是我的查看器的样子:

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,它会像丝绸一样流畅。

【问题讨论】:

  • 如果我将布局 XML 完全重写为基于 LinearLayout,它会像丝绸一样流畅 - 如果是这样,那么为什么要使用 ConstraintLayout,如果你能够实现同样的事情使用LinearLayout?
  • 我在 reddit 上读到人们在性能方面也有类似的问题,显然签署 apk 并运行已发布的版本工作正常。试试看。

标签: android android-recyclerview android-constraintlayout android-viewholder


【解决方案1】:

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

android:layout_height="wrap_content"

如果我为这个属性指定一个固定大小,一切都很好。为确定每一行的视图高度而进行的不断计算可能会导致问题。

【讨论】:

  • 你可以使用setHasFixedSize()来避免不断的计算。
猜你喜欢
  • 2019-04-26
  • 2023-04-05
  • 1970-01-01
  • 2020-12-23
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2019-09-16
  • 1970-01-01
相关资源
最近更新 更多