【问题标题】:Center fixed-size ImageView horizontally in parent ConstraintLayout在父 ConstraintLayout 中水平居中固定大小的 ImageView
【发布时间】:2017-01-26 21:20:05
【问题描述】:

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

但是,有两个问题:ImageView 粘在父级的左侧,我不知道如何使其水平居中 - 我在 Google 上只能找到多个元素的链,但我只想要一个居中。

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

当我这样做的时候,我如何在CardView 之上对ImageView 进行z 排序?

这里的布局:

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

谢谢!

【问题讨论】:

    标签: android android-layout android-constraintlayout


    【解决方案1】:

    docs

    当您向视图的两侧(以及视图大小)添加约束时 对于相同的维度是“固定”或“包装内容”),视图 默认情况下在两个锚点之间居中。

    添加以下约束使ImageView居中。

    app:layout_constraintEnd_toEndOf="parent"
    

    此外,添加比 CardView 更高的标高可以修复 z-index,因为标高会覆盖 z-index。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-10
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      相关资源
      最近更新 更多