如何实现可平滑横竖滚动的Kotlin RecyclerView?现有实现存在异常
解决横竖滚动异常的方案
问题根源分析
- 滚动行为冲突:
HorizontalScrollView和内部的RecyclerView同时设置了app:layout_behavior="@string/appbar_scrolling_view_behavior",导致CoordinatorLayout无法正确处理滚动事件分发。 - 方向不匹配:布局里RecyclerView设置了
android:orientation="horizontal",但代码中给它设置的是垂直方向的LinearLayoutManager,这种矛盾会引发滚动逻辑混乱。 - 布局参数不合理: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
相关产品推荐
相关产品推荐

