Android ConstraintLayout嵌套布局实现:子布局及内部视图占比设置求助
搞定你的ConstraintLayout布局需求
嘿,我来帮你实现这个嵌套布局!先上完整的可运行XML代码,再给你拆解关键设置:
<?xml version="1.0" encoding="utf-8"?> <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"> <!-- 子ConstraintLayout:占父高度1/4,左右底部边距25dp --> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/child_container" android:layout_width="match_parent" android:layout_height="0dp" android:layout_marginLeft="25dp" android:layout_marginRight="25dp" android:layout_marginBottom="25dp" android:background="#E0E0E0" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintHeight_percent="0.25"> <!-- 第一个子视图:占子布局高度70% --> <TextView android:id="@+id/view1" android:layout_width="match_parent" android:layout_height="0dp" android:background="#FF9800" android:gravity="center" android:text="70% Height" android:textColor="#FFFFFF" app:layout_constraintTop_toTopOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintHeight_percent="0.7"/> <!-- 第二个子视图:占子布局高度剩余30% --> <TextView android:id="@+id/view2" android:layout_width="match_parent" android:layout_height="0dp" android:background="#2196F3" android:gravity="center" android:text="30% Height" android:textColor="#FFFFFF" app:layout_constraintTop_toBottomOf="@+id/view1" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintHeight_percent="0.3"/> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>
关键设置拆解:
- 子布局的高度控制:通过
app:layout_constraintHeight_percent="0.25"让子ConstraintLayout占父布局高度的25%(也就是1/4),同时把android:layout_height设为0dp,这样百分比约束才会生效。 - 子布局的边距与定位:设置了
layout_marginLeft、layout_marginRight、layout_marginBottom各25dp,同时通过约束bottom_toBottomOf="parent"、left_toLeftOf="parent"、right_toRightOf="parent"让子布局贴紧父布局的底部和左右(带边距)。 - 子布局内的两个视图:
- 第一个视图用
app:layout_constraintHeight_percent="0.7"占子布局70%高度,约束顶部、左右对齐子布局。 - 第二个视图用
app:layout_constraintHeight_percent="0.3"占30%高度,约束顶部接第一个视图的底部,底部对齐子布局底部,左右对齐子布局,这样两个视图就能填满子布局的高度。
- 第一个视图用
另外注意我用了androidx版本的ConstraintLayout,这是现在官方推荐的,如果你还在用旧的support库,把包名改成android.support.constraint.ConstraintLayout就行,但还是建议升级到androidx哦。
内容的提问来源于stack exchange,提问作者Rob




