使用 ConstraintLayout 在另一个视图下方制作按钮

Make button below another view using ConstraintLayout

我的布局有 1 个 Button(红色背景)和 2 个 ImageView(一个黄色背景,一个蓝色背景),例如

<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:background="#f00"
        android:text="Button"
        android:textSize="30sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <ImageView
        android:layout_width="300dp"
        android:layout_height="300dp"
        android:background="#ff0"
        android:src="@mipmap/ic_launcher"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:background="#00f"
        android:src="@mipmap/ic_launcher_round"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        />

</android.support.constraint.ConstraintLayout>

这是结果图像,Button 显示在 2 ImageView 上方。经过测试,我发现这个问题只发生在 Button 上。如果在我的布局代码中,我删除了 Button,2 保持 ImageView 显示正确。

如何使用 ConstraintLayout 在另一个视图下方居中显示 Button?。任何帮助或建议将不胜感激。

发生这种情况是因为按钮的默认高度为 2dp。看到这个 link

一个简单的解决方法是将 ImageView 的高度设置为 3dp 或更高。

<ImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:elevation="2dp"
    android:src="@mipmap/ic_launcher_round"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

编辑

对于 API below 21 (Lolipop) 这应该不是问题,视图将正确呈现(按照 XML 中的放置顺序)。由于我们要使用 android:elevation 获取 Button 之上的其他视图,因此我们为 API 21+

创建单独的布局资源很重要