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

如何实现可平滑横竖滚动的Kotlin RecyclerView?现有实现存在异常

解决横竖滚动异常的方案

问题根源分析

  1. 滚动行为冲突:HorizontalScrollView 和内部的 RecyclerView 同时设置了 app:layout_behavior="@string/appbar_scrolling_view_behavior",导致CoordinatorLayout无法正确处理滚动事件分发。
  2. 方向不匹配:布局里RecyclerView设置了android:orientation="horizontal",但代码中给它设置的是垂直方向的LinearLayoutManager,这种矛盾会引发滚动逻辑混乱。
  3. 布局参数不合理:RecyclerView的layout_height设为wrap_content,会导致纵向滚动范围计算错误,出现局部滚动异常。

修正步骤

1. 修正布局文件(fragment_standings.xml)

移除RecyclerView上多余的滚动行为属性,调整方向和布局参数:

<!--Table-->
<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior">
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/standings_recycler_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:scrollbars="vertical"
        tools:listitem="@layout/item_standings_table_row" />
</HorizontalScrollView>
  • 只保留外层HorizontalScrollView的appbar_scrolling_view_behavior,让它作为CoordinatorLayout的滚动子容器。
  • 将RecyclerView的orientation改为vertical,和代码中的LinearLayoutManager方向匹配。
  • 把RecyclerView的layout_height设为match_parent,确保纵向滚动范围覆盖整个容器。

2. 确认RecyclerView初始化代码(StandingsFragment.kt)

当前代码中的LinearLayoutManager方向是正确的,保持即可:

private fun initRecyclerView(standings: List<Standing>) {
    binding.standingsRecyclerView.apply {
        layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false)
        adapter = StandingsRVAdapter(
            standings = standings,
            onStandingClicked = onStandingClicked()
        )
    }
}

3. 检查Item布局

确保你的item_standings_table_row布局宽度足够(比如设置为固定宽度或wrap_content后内容超出屏幕),这样HorizontalScrollView才会触发横向滚动。

原理说明

修正后,HorizontalScrollView负责处理横向滚动,内部的RecyclerView负责处理纵向滚动,两者职责明确,CoordinatorLayout只需要监听外层滚动容器的事件,不会再出现滚动冲突。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:01:37