首页 > 解决方案 > 如何针对具有多个宽高比的图像优化 RecyclerView 以避免跳转/滞后/卡顿?

问题描述

我们的应用程序是一个以图像为中心、以时尚为中心的应用程序。它的主屏幕包含一个类似 Instagram 的提要,它从服务器加载图像的 URL 并使用 Glide 加载它。

由于我们使用的是 RecyclerView,因此每次离开屏幕时都会重绘该项目。问题是,这会导致每次用户向下(或向上)滚动时出现卡顿/延迟,并且 RecyclerView 需要重新绘制图像(然后调用adjustViewBounds)以使图像的宽度“填充”屏幕宽度,同时保持比例。

ImageView 的 XML 代码。

<ImageView
    android:id="@+id/homeFeed_IV_lookImage"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitXY"
    app:imageUrl="@{homeFeedItemViewModel.lookImage}"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    tools:src="@drawable/static_image_1" />

绑定适配器。

@BindingAdapter("imageUrl")
fun setImageUrl(imageView: ImageView, url: String?) {
    if (!url.isNullOrEmpty()) {
        imageView.displayImage(url)
    }
}

扩展功能。

fun ImageView.displayImage(url: String = "") {
    Glide.with(context)
            .load(url)
            .apply(RequestOptions().placeholder(R.color.imagePlaceholder)
                    .diskCacheStrategy(DiskCacheStrategy.ALL))
            .into(this)
}

这种“滞后/卡顿”会带来不愉快的体验。有什么方法可以使 RecyclerView 中的图像重绘更平滑?

标签: androidandroid-recyclerviewandroid-glidefresco

解决方案


您可以通过使用固定大小的 ImageView 来提高性能。如果您控制后端并且有可能包含有关图像的更多信息而不仅仅是 URL(以便您在提要有效负载中包含宽度和高度或图像纵横比)。


推荐阅读