简单介绍

约束布局 ConstraintLayout 是一个ViewGroup,主要解决布局嵌套过多,从而在布局加载时,就要耗费了许多内存,影响了项目的整体的一个客户体验感,以及屏幕适配。所以约束布局也是项目中,比不可少的部分!

这里有官方文档,帮助大家更详细的去了解一下:

https://developer.android.google.cn/reference/android/support/constraint/ConstraintLayout

手动操作:https://blog.csdn.net/guolin_blog/article/details/53122387


如何使用

1.第一步添加依赖、布局设置为ConstranitLaoyout:

implementation 'com.android.support.constraint:constraint-layout:1.1.3'

 

2.相对定位:相对定位在约束布局中是最基本的模块,主要分为横向、纵向的约束关系:

(1)相对定位的属性:

   

 

  • 横向: left、Right、Start、End.
layout_constraintLeft_toLeftOf //控件1的左侧放置到控件2的左边layout_constraintLeft_toRightOf //控件1的左侧放置到控件2的右边layout_constraintRight_toLeftOf //控件1的右侧放置到控件2的左边layout_constraintRight_toRightOf //控件1的右侧放置到控件2的右边layout_constraintTop_toTopOf //控件1的顶部放置到控件2的顶部layout_constraintTop_toBottomOf //控件1的顶部放置到控件2的底部layout_constraintBottom_toTopOf //控件1的底部放置到控件2的顶部layout_constraintBottom_toBottomOf //控件1的底部放置到控件2的底部

 

  • 纵向:Top、Bottom、Baseline:
layout_constraintStart_toEndOf //控件1的起始边放置到控件2的尾部layout_constraintStart_toStartOf //控件1的起始边放置到控件2的起始边layout_constraintEnd_toStartOf //控件1的尾部放置到控件2的起始边layout_constraintEnd_toEndOf //控件1的尾部放置到控件2的尾部
//Baseline指的是文本基线,当两个文本高度不同,也可以对齐的方式layout_constraintBaseline_toBaselineOf 

 

  • 角度定位:可以用一个角度和一个距离来约束两个空间的中心
app:layout_constraintCircle="@+id/TextView1"app:layout_constraintCircleAngle="120"(角度)app:layout_constraintCircleRadius="150dp"(距离)

 

3.边距:

  • margin
ConstraintLayout的边距常用属性如下:android:layout_marginStartandroid:layout_marginEndandroid:layout_marginLeftandroid:layout_marginTopandroid:layout_marginRightandroid:layout_marginBottom

这里注意了控件必须在布局里约束一个相对位置,否则外边距不生效的。

 

  •  GONE MARGIN 那么这里介绍这个特性,在其他布局中有一个这样的问题,就是当控件A向控件B添加了约束,控件B隐藏后,控件B并不能改变他的边距,导致布局不美观,那么GONE MARGIN 就很好的解决了这个问题。
 ConstraintLayout的Gone margin常用属性如下: layout_goneMarginStart layout_goneMarginEnd layout_goneMarginLeft layout_goneMarginTop layout_goneMarginRight layout_goneMarginBottom

4.居中和倾向

  • 居中

 

一般我们在其他布局当中只需要把layout_centerInParent设为true即可,那么在约束布局当中需要在两个控件之间添加约束

 ConstraintLayout的居中常用属性如下: app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent"