You need to enable JavaScript to run this app. 如何配置RecyclerView避免其在BottomSheet中渲染屏幕外不可见项
优惠活动
大模型
产品
解决方案
定价
更多

如何配置RecyclerView避免其在BottomSheet中渲染屏幕外不可见项

问题根因

这个问题的本质是BottomSheetBehavior仅通过偏移调整容器位置,不会修改子RecyclerView的测量高度:你给RecyclerView设置的android:layout_height="match_parent"会让它在测量阶段拿到父布局CoordinatorLayout的全高作为自身可用高度,LayoutManager会按照全高来预创建和布局item,哪怕这些item所在的区域当前被移出屏幕外,RecyclerView也不会触发回收,最终导致大量不可见item被实例化、执行绘制逻辑,带来不必要的性能损耗。

解决方案

以下方案均聚焦于RecyclerView本身逻辑,不需要用到ViewStub:

方案1:自定义LayoutManager限制布局范围

重写你使用的LayoutManager(以LinearLayoutManager为例),禁用默认的额外预加载空间,同时布局完成后主动回收不可见item,侵入性最低:

class BottomSheetOptimizedLinearLayoutManager(context: Context) : LinearLayoutManager(context) {
    override fun calculateExtraLayoutSpace(state: RecyclerView.State, extraLayoutSpace: IntArray) {
        // 禁用默认额外预加载空间,避免提前创建屏幕外item
        extraLayoutSpace[0] = 0
        extraLayoutSpace[1] = 0
    }

    override fun onLayoutChildren(recycler: RecyclerView.Recycler?, state: RecyclerView.State?) {
        super.onLayoutChildren(recycler, state)
        if (state?.isPreLayout == true || recycler == null) return
        // 回收所有超出当前可见区域底部的item
        val visibleBottom = height - paddingBottom
        for (i in childCount - 1 downTo 0) {
            val child = getChildAt(i) ?: continue
            if (getDecoratedTop(child) >= visibleBottom) {
                removeAndRecycleView(child, recycler)
            } else {
                // 列表从上到下布局,遇到第一个在可见区域内的item即可停止遍历
                break
            }
        }
    }
}

使用时直接替换原有LayoutManager即可:

recyclerView.layoutManager = BottomSheetOptimizedLinearLayoutManager(context)

方案2:监听BottomSheet状态动态调整RecyclerView高度

监听BottomSheetBehavior的滑动偏移,动态修改RecyclerView的布局高度,让它始终等于当前实际可见高度,LayoutManager会自动按当前高度布局并回收超出的item:

  1. 先把布局中RecyclerView的android:layout_height属性从match_parent改为wrap_content
  2. 代码中添加滑动监听:
val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheetRecyclerView)
bottomSheetBehavior.addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() {
    override fun onStateChanged(bottomSheet: View, newState: Int) {}

    override fun onSlide(bottomSheet: View, slideOffset: Float) {
        val parentHeight = (bottomSheet.parent as View).height
        val currentHeight = (bottomSheetBehavior.peekHeight + (parentHeight - bottomSheetBehavior.peekHeight) * slideOffset).toInt()
        bottomSheet.updateLayoutParams {
            height = currentHeight
        }
    }
})

方案3:自定义RecyclerView重写测量逻辑

不需要额外依赖BottomSheet的回调,自定义RecyclerView自动计算可见区域高度,按可见高度完成测量:

class BottomSheetOptimizedRecyclerView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : RecyclerView(context, attrs, defStyleAttr) {
    private val visibleRect = Rect()

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        getLocalVisibleRect(visibleRect)
        val visibleHeight = visibleRect.height()
        if (visibleHeight > 0) {
            // 按当前实际可见高度测量,让LayoutManager只布局可见范围内的item
            super.onMeasure(widthSpec, MeasureSpec.makeMeasureSpec(visibleHeight, MeasureSpec.EXACTLY))
        } else {
            super.onMeasure(widthSpec, heightSpec)
        }
    }
}

使用时直接替换布局文件中的androidx.recyclerview.widget.RecyclerView为这个自定义类即可。

内容的提问来源于stack exchange,提问作者l33t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 03:24:03