ConstrainLayout详解

发布时间:2023-05-19

一、介绍

ConstrainLayout是Android Studio 2.3之后新增的布局组件,它是基于ConstraintLayout算法库实现的,旨在提供更灵活、更高效的布局方式。它能够快速创建复杂的布局,以解决在早期的开发过程中遇到的难点。

二、使用

1、基本概念

ConstrainLayout布局中有好几个重要的概念需要理解。

  • Constraint:表示一个对象应该相对于其他对象的位置。
  • Anchor:Constraint连接到视图的一端,通常是边缘。需要在布局中定义锚点,以便ConstrainLayout可以找到这些锚点。
  • Horizontal Bias/Vertical Bias:可以沿水平和/或垂直轴调整视图的位置。
  • Gone Margin:当视图是gone时,Gone Margin指定该视图的空间大小,而不是视图的实际大小。这有助于避免因消失而导致的裂缝或布局问题。

2、创建布局

创建一个ConstrainLayout布局很简单,只需按照下面的示例中进行代码编写即可。

<?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"
    tools:context=".MainActivity">
    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="BUTTON"
        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,并将它放在布局的中心。这是通过将Button的每个边缘的Constraint(即上下左右的约束)设置为其父控件的相应边缘,使Button在布局中居中。

3、约束

为了让视图相对于其他视图定位,我们需要使用constraint来指定约束关系。下面是一些常用的约束规则。

  • app:layout_constraintLeft_toRightOf:指定视图的左边缘相对于目标视图的右边缘的约束关系。
  • app:layout_constraintStart_toEndOf:指定视图的起始端与目标视图的结束端相对的约束关系。
  • app:layout_constraintTop_toBottomOf:指定视图的顶部与目标视图的底部对齐的约束关系。
  • app:layout_constraintEnd_toStartOf:指定视图的结束端与目标视图的起始端相对的约束关系。
  • app:layout_constraintBottom_toTopOf:指定视图的底部与目标视图的顶部对齐的约束关系。
  • app:layout_constraintVertical_bias:指定视图在垂直方向上相对于目标视图的偏移,值从0到1。
  • app:layout_constraintHorizontal_bias:指定视图在水平方向上相对于目标视图的偏移,值从0到1。

4、删除约束

要在ConstrainLayout布局中删除约束,请在视图的约束属性中手动删除相应的约束。或者,选择一个视图并右键单击它以打开“约束”属性菜单。这里可以删除指定方向的约束关系。

5、Gone时的计算方式

视图消失时,需要清除与该视图相关的约束。这样才能避免有“空隙”在布局中。同样,当一个视图是gone时,Gone Margin可以指定该视图的空间大小,而不是视图的实际大小。

三、优点

1、性能优秀

在大多数情况下,使用ConstrainLayout的布局比其他布局组件快。相对于LinearLayout和RelativeLayout来说,ConstrainLayout性能出类拔萃,特别是在复杂布局的情况下。

2、布局灵活

ConstrainLayout允许根据个人需求创建布局。一个对象可以连接到另一个对象之上,在应用后其位置将被偏移。此外,ConstrainLayout提供了水平和垂直方向上的偏移支持。

3、支持链式约束

当一系列的视图需要一起移动时,使用链式约束支持始终是最好的选择,因为它比设置多个独立的约束更简单、更有效。

四、结论

ConstrainLayout是一种高效、强大、灵活的布局方式,它可以快速创建复杂的布局。它使用起来很简单,只需要一些基本的理解就能在应用程序中使用它。因此,ConstrainLayout在Android开发中具有极高的实际价值,并且应该成为每个Android开发者工具箱中必不可少的一部分。