NestedScrollView嵌套ConstraintLayout滚动失效 已设fillViewport仍无效
核心问题根因
- 内层ConstraintLayout设置了
android:layout_height="match_parent",即使开启了fillViewport="true",它的实际高度会完全等于外层NestedScrollView的高度,不会出现内容溢出,NestedScrollView自然没有可触发滚动的差值 - RecyclerView目前的约束配置是顶部对齐交易标题、底部对齐ConstraintLayout父布局,加上高度设为
0dp、开启app:layout_constrainedHeight="true",会被ConstraintLayout强行拉满剩余的所有屏幕空间,进一步把整体布局的高度锁死在屏幕尺寸,完全没有滚动空间 - RecyclerView默认开启嵌套滚动,会直接拦截触摸滑动事件,即使出现内容溢出,也会因为事件分发冲突导致滚动失效
可直接落地的修复方案
- 调整内层ConstraintLayout的高度属性,把
android:layout_height="match_parent"改为android:layout_height="wrap_content",让布局的高度完全由内部所有子View的内容撑开,当内容总高度超过屏幕尺寸时,NestedScrollView自然可以响应滚动 - 调整RecyclerView的属性与约束:
- 把
android:layout_height="0dp"改为android:layout_height="wrap_content" - 移除
app:layout_constraintBottom_toBottomOf="parent"的约束,不再让RecyclerView强行对齐父布局底部 - 移除不再生效的
app:layout_constrainedHeight="true"配置 - 添加
android:nestedScrollingEnabled="false"配置,关闭RecyclerView自身的滚动事件分发能力,把滑动响应完全交给外层的NestedScrollView
- 把
- 调整ProgressBar的约束规则:移除它原本对齐父布局底部的配置,改为对齐RecyclerView的中心位置,避免ProgressBar的约束关系把整体布局高度重新拉成屏幕等高
调整后RecyclerView的关键代码参考:
<androidx.recyclerview.widget.RecyclerView android:id="@+id/recycler_view_wallet" android:layout_width="match_parent" android:layout_height="wrap_content" android:nestedScrollingEnabled="false" android:layout_margin="@dimen/content_edge_margin_horizontal" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toBottomOf="@id/textview_transaction_title" />
- 注意场景边界:这套方案适合交易记录条目不多的页面,如果列表条目超过几十条,不建议把整列内容塞到NestedScrollView里,会因为一次性加载所有列表项出现内存占用过高、滑动卡顿的问题,这种场景还是要保留RecyclerView自身的滚动能力。
内容的提问来源于stack exchange,提问作者Ramya
相关产品推荐
相关产品推荐

