在父级ConstraintLayout中水平居中固定大小的ImageView

11

我有一个非常简单的布局:一个填满整个屏幕的 ConstraintLayout,其中有一个大的 CardView。顶部有一个 ImageView,它在 CardView 的一半上方(实际上不是一半,但你明白我的意思)。

然而,有两个问题: ImageView 粘着父元素的左边,我不知道如何使其水平居中 - 我在Google上找到的都是用于多个元素的链式布局,但我只想要一个居中的元素。

布局编辑器对我来说非常糟糕。我的第一个抱怨是似乎无法创建与父元素的约束。然后我尝试通过按下“居中对齐”按钮将 ImageView 在父元素中水平居中。这会增加 CardView 的宽度,但对 ImageView 没有任何影响。

顺便问一下,我该如何将 ImageView 放置在 CardView 之上呢?

这里是布局:

<?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:background="@color/colorPrimaryDark">
<android.support.v7.widget.CardView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginBottom="32dp"
    android:layout_marginEnd="32dp"
    android:layout_marginStart="32dp"
    android:layout_marginTop="160dp"
    app:cardCornerRadius="12dp"
    app:cardElevation="32dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent">

</android.support.v7.widget.CardView>

<ImageView
    android:layout_width="200dp"
    android:layout_height="200dp"
    android:layout_marginTop="40dp"
    android:scaleType="centerCrop"
    android:src="@drawable/re_zero"

    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

谢谢!

1个回答

16
根据文档

当你在视图两侧都添加约束时(且对于同一维度的视图大小为“fixed”或“wrap content”),默认情况下,视图将居中于两个锚点之间。

添加以下约束可以使ImageView居中。
app:layout_constraintEnd_toEndOf="parent"

还有,添加比CardView更高的高度可以修复z-index问题,因为高度将覆盖z-index。


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