ConstraintLayout中RecyclerView高度适配:view_b最多占1/3父布局空间
解决方案
直接通过ConstraintLayout的属性组合就能实现需求,无需额外代码,具体布局代码如下:
<androidx.constraintlayout.widget.ConstraintLayout 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"> <!-- 顶部RecyclerView:view_a --> <androidx.recyclerview.widget.RecyclerView android:id="@+id/view_a" android:layout_width="match_parent" android:layout_height="0dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toTopOf="@id/view_b"/> <!-- 底部RecyclerView:view_b --> <androidx.recyclerview.widget.RecyclerView android:id="@+id/view_b" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintTop_toBottomOf="@id/view_a" app:layout_constraintHeight_percent="0.33" app:layout_constraintHeight_max="wrap"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键属性说明
- view_a:
- 高度设为
0dp,配合上下约束(顶贴父布局顶部、底贴view_b顶部),自动填充view_b之外的剩余空间,无论view_b高度如何变化,都会占满剩余区域。
- 高度设为
- view_b:
- 高度设为
wrap_content,实现内容自适应高度; app:layout_constraintHeight_percent="0.33"限制最大高度为父布局的1/3;app:layout_constraintHeight_max="wrap"确保百分比限制仅在内容高度超过1/3时生效,内容较少时仍保持自适应高度。
- 高度设为
这套组合完美覆盖两种场景:
- 当view_b内容少(如仅1个item),它会自适应内容高度,view_a占据剩余全部空间;
- 当view_b内容过多时,会被限制在父布局1/3高度内并可滚动,view_a占据剩余2/3空间。
内容的提问来源于stack exchange,提问作者Thore
相关产品推荐
相关产品推荐

