Android XML布局FrameLayout嵌套ConstraintLayout仅显示绿色区域问题
问题根因
你这个问题的核心是布局属性和父容器类型不匹配:
- 你给两个子
ConstraintLayout设置的app:layout_constraintXXX系列约束属性,只有当它们的父容器是ConstraintLayout时才会生效,而你当前的根布局是FrameLayout - FrameLayout的默认布局规则是所有子View都堆叠在左上角,你两个子View的宽度都是100dp、高度都是匹配父容器,后添加的绿色
ConstraintLayout会直接覆盖在红色ConstraintLayout上方,所以最终你只能看到绿色区域。
修复方案
两种可选方案都可以实现你要的红、绿矩形左右排列的效果:
方案1:把根布局改成ConstraintLayout
直接修改根节点标签即可,你已经写好的子View约束规则可以直接生效:
<?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="200dp" android:layout_height="100dp"> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/first_constrain" android:layout_width="100dp" android:layout_height="match_parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:background="#FF0000" /> <androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/second_constrain" android:layout_width="100dp" android:layout_height="match_parent" app:layout_constraintStart_toEndOf="@+id/first_constrain" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:background="#00FF00"> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.constraintlayout.widget.ConstraintLayout>
方案2:保留FrameLayout根布局,给第二个子View设置左边距
不需要修改约束,直接给绿色的ConstraintLayout加android:layout_marginStart="100dp"属性即可,利用FrameLayout的边距规则让两个View错开:
<androidx.constraintlayout.widget.ConstraintLayout android:id="@+id/second_constrain" android:layout_width="100dp" android:layout_height="match_parent" android:layout_marginStart="100dp" android:background="#00FF00"/>
内容的提问来源于stack exchange,提问作者Roman Kazmin
相关产品推荐
相关产品推荐

