如何为RecyclerView底部预留空间以放置固定展示的按钮
问题原因
你布局出问题的核心原因是垂直LinearLayout里的RecyclerView设置了android:layout_height="match_parent",会直接占满父布局剩余的全部高度,后面的按钮布局会被挤出屏幕可视区域。你给RecyclerView加的底部padding是内容内边距,只会调整列表内部内容的展示位置,不会改变RecyclerView自身的高度,所以无效。
解决方案
方案1:直接修改现有LinearLayout布局
只需要调整RecyclerView的两个属性:
- 将
android:layout_height从match_parent改为0dp - 给RecyclerView添加
android:layout_weight="1"属性,让它自动占用标题栏和底部按钮栏之外的剩余高度
如果需要列表滚动到底部时,最后一项不会被底部padding挡住,可以额外添加android:clipToPadding="false"属性。
改后的完整代码如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:id="@+id/title" android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="20dp" android:gravity="top|center" android:orientation="horizontal"> <ImageView android:layout_width="45dp" android:layout_height="45dp" android:layout_marginEnd="10dp" android:gravity="center" android:scaleType="fitXY" android:src="@drawable/accueil" app:tint="@color/orange" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/redressed" android:gravity="center" android:text="@string/app_name" android:textColor="@color/bleu" android:textSize="30sp" /> </LinearLayout> <androidx.recyclerview.widget.RecyclerView android:id="@+id/list_recyclerView" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:paddingBottom="60dp" android:clipToPadding="false"/> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Generer horaire" android:layout_gravity="start" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Ajouter tache" android:layout_gravity="end" /> </LinearLayout> </LinearLayout>
方案2:改用ConstraintLayout实现(更推荐)
如果后续有更复杂的布局需求,用ConstraintLayout性能更好,也更容易调整控件位置,不需要嵌套多层LinearLayout。
内容的提问来源于stack exchange,提问作者Vincent Gagnon
相关产品推荐
相关产品推荐

