Android 约束布局无法按预期工作

标签 android xml android-layout android-constraintlayout

我有一个根标签为

的 Activity
androidx.constraintlayout.widget.ConstraintLayout

我在此 Activity 中包含 3 个布局文件并垂直列出它们。中间一个下面的约束不起作用

    app:layout_constraintTop_toBottomOf="@+id/lay1"
    app:layout_constraintBottom_toTopOf="@+id/lay3"

我不明白为什么中间那个占据了整个屏幕而不是从顶部的底部开始到底部的顶部结束。你能帮帮我吗?

Activity :

<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">

    <include
        android:id="@+id/lay1"
        layout="@layout/empty_linear_layout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <include
        android:id="@+id/lay2"
        layout="@layout/empty_linear_layout"
        app:layout_constraintBottom_toTopOf="@+id/lay3"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/lay1" />

    <include
        android:id="@+id/lay3"
        layout="@layout/empty_linear_layout"
        android:layout_width="match_parent"
        android:layout_height="50dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

empty_linear_layout.xml :

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:text="button" />

</LinearLayout>

最佳答案

如果你想覆盖layout_ <include> 上的参数布局,你必须同时指定 layout_widthlayout_height .来自 the developer docs :

However, if you want to override layout attributes using the <include> tag, you must override both android:layout_height and android:layout_width in order for other layout attributes to take effect.

因此将这两行添加到您的第二个 View :

android:layout_width="0dp"
android:layout_height="0dp"

(注意对于ConstraintLayout0dp表示匹配约束条件)

关于Android 约束布局无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57339306/

相关文章:

android - 找不到类 'android.graphics.drawable.RippleDrawable'

Android EditText 不打开键盘

sql - 我如何找出 Postgres 中的大 TEXT 字段有多大?

android - Android 上带有远程 View 的自定义通知

android - 如何更改 textview 超链接的颜色?

android - 为什么 FrameLayout 没有在我的布局中正确设置 Z 顺序?

java - 屏幕截图与显示 View 不相似

android - 将 Firebase 中的重复对象加载到 ListView 中

c# - XPathResultType 定义错误?

c# - 将 xml 值转换为字符串(使用 c#)