[译] ConstraintLayout深入系列之中心点对齐

作者: android00 发布时间: 2017-09-07 浏览: 6255 次 编辑

原文:ConstraintLayout tricks & tips Centring
作者:Mark Allison


中心点对齐

在 Android 设计布局中,我们常常遇到需要根据父组件、相邻组件甚至是相邻组件的边来进行中心点对齐。本文将讲解如何使用 ConstraintLayout 来满足这些中心点对齐的需求。

需要中心点对齐的 Views 一般是有自己不定的内容大小的,经常定义的宽高是 android:layout_[width|height]="wrap_content" 。本文中使用到的例子也会按照这个模式来使用。

目录:

  1. [译] ConstraintLayout基础系列之约束(constraints)
  2. [译] ConstraintLayout基础系列之Chains链
  3. [译] ConstraintLayout基础系列之参照线guidelines
  4. [译] ConstraintLayout基础系列之尺寸横纵比 dimensions
  5. [译] ConstraintLayout深入系列之代替常见布局
  6. 【译】ConstraintLayout深入系列之中心点对齐

相对父组件进行居中对齐

在父组件中居中对齐,可以通过对 View 的某个坐标轴的两个边的锚点设置约束条件到父组件相对应的边来进行居中。比如,让子组件垂直居中的话,我们需要设置 topbottom 上下边的锚点约束,而水平居中的话,则需要设置 startend 左右边的锚点约束。此处使用 startend 而不是用 leftright 是为了更好的 RTL (Right to Left)布局体验。

centring_parent.gif

在这个例子中,我们设置 View 的 start 边到父组件的 start 边,同时设置了 end 边到父组件的 end 边。

在 XML 设置相对父组件居中

在 XML 其实跟视图编辑器是一样的意思,设置好 app:layout_constraintStart_toStartOf="parent" 以及 app:layout_constraintEnd_toEndOf="parent",如下:

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:layout_constraintTop_toBottomOf="parent"

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"/>

相对邻组件的中心点居中

这种中心点居中跟相对父组件的中心点居中差不多,唯一的区别就是设置的约束是向相邻组件而不是向父组件,如下图操作:

centring_sibling_middle.gif

在 XML 中设置对邻组件居中

在 XML 源码中也是一样,非常相似,唯一不同就是约束指向邻组件的 android:id 而不是 parent

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:layout_constraintTop_toTopOf="@+id/imageView"

app:layout_constraintBottom_toBottomOf="@+id/imageView"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"/>

相对邻组件的某一边中心点居中

最后要讲解的这个中心点居中,在其他布局中非常不好实现,对于此 Material Design 指南中已经提到了 如何让浮动按钮对齐到某个组件的边缘 ,通过 ConstraintLayout 可以轻松实现这个效果。假如,我们需要设置垂直向的居中到某一边,那么就设置 View 的 topbottom 边的锚点约束到邻组件的那条边的同一边的中心锚点上,如下图所示:

centring_sibling_edge.gif

在 XML 中设置对邻组件某边居中

在 XML 中也是非常的简单明了,直接就是设置约束到同一个锚点,app:layout_constraintTop_toBottomOf="@+id/imageView"app:layout_constraintBottom_toBottomOf="@+id/imageView",代码如下:

<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

app:layout_constraintTop_toBottomOf="@+id/imageView"

app:layout_constraintBottom_toBottomOf="@+id/imageView"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintEnd_toEndOf="parent"/