You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

RecyclerView的addOnScrollListener异常,CoordinatorLayout内canScrollVertically(1)始终为true

问题原因
  • 你的RecyclerView同时配置了app:layout_behavior="@string/appbar_scrolling_view_behavior"和app:layout_anchor="@id/app_bar_layout"属性,canScrollVertically()的原生判断逻辑不会计入AppBarLayout的滚动偏移量,导致就算列表内容完全滑到底部,返回值依然为true。
  • appbar_scrolling_view_behavior本身已经实现了自动将RecyclerView放置在AppBarLayout下方的能力,额外添加anchor属性会干扰RecyclerView自身的滚动范围计算。
解决方案

方案1:修改布局属性(优先推荐)

直接删除RecyclerView的以下两个属性即可:

app:layout_anchor="@id/app_bar_layout"
app:layout_anchorGravity="bottom"

修改完成后原生的canScrollVertically(1)判断即可正常生效。

方案2:替换滚动到底部的判断逻辑

如果不需要修改布局,可直接通过LayoutManager判断最后可见item的位置来替代原生判断,该方案不受嵌套滚动容器的影响,兼容性更好:

getDataBinding().shipmentRecyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
    override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
        super.onScrollStateChanged(recyclerView, newState)
        if (newState == RecyclerView.SCROLL_STATE_IDLE) {
            val layoutManager = recyclerView.layoutManager as LinearLayoutManager
            // 最后一个完全可见的item位置
            val lastVisibleItemPosition = layoutManager.findLastCompletelyVisibleItemPosition()
            val totalItemCount = layoutManager.itemCount
            // 总item数大于0,且最后一个可见item是最后一条,说明滚动到底部
            if (totalItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1) {
                Log.e(TAG, "onScrollStateChanged 2: This is the bottom shipmentRecyclerView")
                if (viewModel.currentPage.get()!! < viewModel.totalPages.get()!!) {
                    viewModel.getShipmentByPage(
                        viewModel.currentPage.get()!! + 1,
                        viewModel.request.get()
                    )
                }
            }
        }
    }
})

如果使用的是GridLayoutManager,上述逻辑无需修改可直接复用。

内容的提问来源于stack exchange,提问作者T. Boubaker

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 07:45:02