阻止空的ConstraintLayout最大化拉伸

3

当我从我的约束布局中删除所有视图时,我希望它的高度为0dp(类似于wrap_content),但它会尽可能地拉伸。

有没有文档记录的方法可以做到这一点?我的意思是除了设置最大高度为0或隐藏它之外。

我已经尝试过使用app:layout_constrainedHeight="true""wrap_content",但它不起作用。

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

<android.support.constraint.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_constrainedHeight="true"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent">

</android.support.constraint.ConstraintLayout>

1个回答

1

我找不到合适的解决方案。


我想到的最简单的解决方法是添加一个额外的视图,其height=0,并且永远不要将其删除:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <FrameLayout
            android:id="@+id/somethingWithNoHeight"
            android:layout_width="match_parent"
            android:layout_height="0dp" />

        <!--<TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Lorem ipsum" />-->
    </android.support.constraint.ConstraintLayout>
</android.support.constraint.ConstraintLayout>

我认为你应该提交一个错误报告,以确保开发人员知道这样的问题


1
我也走过这条路,但我看到了两个不便之处:a)索引。你需要记住每个子索引都会增加,这可能会导致不那么明显的错误;b)约束。同样,你可能会忘记这个视图,并且花费大量时间在代码中玩弄约束,而不理解它们为什么会表现出这种方式。 - NDQuattro
2
也许更好的方法是扩展ConstraintLayout并覆盖onViewAddedonViewRemoved以设置visibility=View.GONE,如果它没有子项的话,这样自身就可以工作。由于您将ConstraintLayout用作根视图,因此在GONE视图上的约束仍应该起作用。 - Andrey Busik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接