RecyclerView高度适配:内容少时包裹,满时不超BottomAppBar
解决RecyclerView自适应高度(内容少时包裹,内容多时撑满至BottomAppBar)
核心修改思路
- 将RecyclerView的高度从强制撑满的
0dp改为wrap_content,让它默认包裹内容 - 保留底部约束,同时添加高度规则,确保内容过多时自动撑满到BottomAppBar上方的边界
修改后的完整布局代码
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@color/shading" tools:context=".MainActivity"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginBottom="?android:attr/actionBarSize" android:background="@color/shading"> <ImageView android:id="@+id/logo" android:layout_width="120dp" android:layout_height="60dp" android:src="@drawable/ic_logo" app:layout_constraintBottom_toTopOf="@+id/list_projects" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <androidx.recyclerview.widget.RecyclerView android:id="@+id/list_projects" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:background="@drawable/shape_list_item_projects" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/logo" app:layout_constraintHeight_default="wrap" app:layout_constraintHeight_max="wrap" /> </androidx.constraintlayout.widget.ConstraintLayout> <com.google.android.material.bottomappbar.BottomAppBar android:id="@+id/bottomAppBar" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_gravity="bottom" app:backgroundTint="@color/white" app:fabCradleRoundedCornerRadius="25dp" app:fabCradleMargin="5dp" app:hideOnScroll="false" app:menu="@menu/menu_main_activity" /> <com.google.android.material.floatingactionbutton.FloatingActionButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_outline_add_circle_outline_24" app:backgroundTint="@color/white" app:layout_anchor="@id/bottomAppBar" app:maxImageSize="40dp" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>
关键修改点说明
android:layout_height="wrap_content":让RecyclerView在内容较少时自动收缩,仅包裹现有列表项app:layout_constraintHeight_default="wrap":指定ConstraintLayout优先采用包裹内容的高度计算逻辑app:layout_constraintHeight_max="wrap"+ 底部约束:当内容足够多时,RecyclerView会自动撑满到父布局底部(也就是BottomAppBar上方的预留空间)
如果之前设置宽度为200dp是为了视觉美观,可以保留android:layout_width="200dp",同时添加app:layout_constraintHorizontal_bias="0.5"让列表水平居中,效果会更协调。
内容的提问来源于stack exchange,提问作者Sterling Duchess
相关产品推荐
相关产品推荐

