Kotlin+Firebase开发购物APP时RecyclerView可滚动但无法滑至底部求助
问题修复方案
问题根源
RecyclerView无法滚动到最底部的核心原因是Activity中NavHostFragment的高度配置错误,导致Fragment底部被BottomNavigationView遮挡,所以RecyclerView最后一个item的底部内容无法显示。
修复步骤
第一步:修改Activity布局中的NavHostFragment配置
把nav_host_fragment的android:layout_height属性从match_parent改为0dp(ConstraintLayout中的match_constraint,会自动适配上下约束之间的可用空间),修改后的代码如下:
<fragment android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" <!-- 把这里的match_parent改成0dp --> android:layout_height="0dp" app:defaultNavHost="true" app:layout_constraintBottom_toTopOf="@id/nav_view" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" app:navGraph="@navigation/mobile_navigation"/>
第二步(可选优化):给RecyclerView增加底部内边距
为了避免最后一个item太贴近底部导航栏,显示效果更美观,可以给Fragment中的RecyclerView增加底部内边距,同时关闭裁剪padding区域的属性:
<androidx.recyclerview.widget.RecyclerView android:id="@+id/rv_dashboard_items" android:layout_width="match_parent" android:layout_height="match_parent" android:visibility="gone" <!-- 新增以下两个属性 --> android:paddingBottom="16dp" android:clipToPadding="false" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/>
原理解释
在ConstraintLayout中,如果一个View同时设置了顶部和底部的约束,想要让View的高度自动填充两个约束之间的剩余空间,必须将layout_height设为0dp。之前设置的match_parent会让NavHostFragment的高度直接等于父布局的总高度,忽略底部layout_constraintBottom_toTopOf="@id/nav_view"的约束,导致Fragment的底部区域被底部导航栏遮挡,自然无法滚动到RecyclerView的最底部。
内容的提问来源于stack exchange,提问作者Rudra Raina
相关产品推荐
相关产品推荐

