You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ConstraintLayout设置wrap_content时如何排除指定子控件不参与高度计算

解决方案

方案1:使用ConstraintLayout原生属性(推荐)

ConstraintLayout 2.0.0及以上版本提供了专门的属性app:layout_constraintIncludeInWrap,用来指定子View是否参与父布局wrap_content的尺寸计算,设置为false即可实现你的需求:既保留子View的约束规则,又不会撑大父布局。
你只需要给需要排除的FrameLayout添加该属性即可,修改后代码如下:

<FrameLayout
    android:layout_width="110dp"
    android:layout_height="250dp"
    android:background="@color/colorPrimary"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/button2"
    app:layout_constraintTop_toBottomOf="@+id/button2"
    <!-- 新增以下属性 -->
    app:layout_constraintIncludeInWrap="false" />

如果你的项目依赖的ConstraintLayout版本低于2.0,升级依赖即可:

implementation "androidx.constraintlayout:constraintlayout:2.1.4"

方案2:兼容旧版本方案

如果不想升级依赖,可以将需要参与父布局高度计算的前三个控件嵌套进一个垂直方向的wrap_content布局中,父布局高度由这个嵌套布局决定,FrameLayout依然可以正常约束到button2的位置,不会撑大父布局:

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:background="@color/colorAccent"
    >

    <!-- 嵌套布局,父布局高度由该布局高度决定 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent">

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Button one" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Button two" />

        <TextView
            android:id="@+id/status_text_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginTop="30dp"
            android:text="Collaps"
            android:textSize="30sp" />

    </LinearLayout>

    <FrameLayout
        android:layout_width="110dp"
        android:layout_height="250dp"
        android:background="@color/colorPrimary"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/button2"
        app:layout_constraintTop_toBottomOf="@+id/button2" />

</androidx.constraintlayout.widget.ConstraintLayout>

内容的提问来源于stack exchange,提问作者Igor Fridman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:42:03