具有嵌套ViewGroup的ViewGroup

时间:2019-03-19 17:18:24

标签: android xml android-layout

我面临一个奇怪的问题。 例如,我们有以下布局:

<android.support.constraint.ConstraintLayout 
...
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000">

<LinearLayout
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toRightOf="parent"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#f00"/>

</LinearLayout>
</android.support.constraint.ConstraintLayout>

我们的屏幕将变黑。如果将LinearLayout替换为FrameLayout或ConstraintLayout,结果相同。

但是如果将第一个LinearLayout替换为RelativeLayout,屏幕将变成红色! 就我而言,我需要像RelativeLayout这样的行为,但是应该使用LinearLayout。 怎么可能? 非常感谢!

1 个答案:

答案 0 :(得分:0)

尝试以下

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">
    <LinearLayout
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        app:layout_constraintVertical_weight="1"
        android:orientation="vertical">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#f00"></LinearLayout>
    </LinearLayout> </android.support.constraint.ConstraintLayout>

如果超级父级是LinearLayout而不是ConstraintLayout,请将app:layout_constraintVertical_weight="1"更改为android:layout_weight="1"并删除其他不必要的代码。如果超级父项是相对布局,则只需删除“权重”参数并添加以下内容。

android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
相关问题