# ConstraintDemo **Repository Path**: ouyangpengdev/ConstraintDemo ## Basic Information - **Project Name**: ConstraintDemo - **Description**: a demo for ConstraintLayout - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-03-23 - **Last Updated**: 2021-03-23 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ConstraintLayout,让布局更优雅。 ### 一、为什么要用ConstraintLayout ![image.jpg](https://note.youdao.com/yws/public/resource/3631121d9411925634e11c66f1e8f601/xmlnote/C3F2CE1DACBD405BB47638C811E32C48/11854) 上图是网易100分的选课首页,在Banner图的下部是推荐类目模块,其中数学、语言、小低和小高分别是推荐类目Item。可见每个类目的子类目个数是不确定的,根据个数的不同,子类目的排列方式也不一样。 现在我们来实现Item的布局。如果用LinearLayout、RelativeLayout和FrameLayout去实现Item布局,我目前想到的最低也需要两层布局。如下所示: ``` ``` 可以发现没有一种布局容器是可以单靠自己搞定这个布局的,需要嵌套不同布局。这样布局层级增加,布局计算时间也加长了。这些都是传统布局存在的问题,概括起来有以下三点: + 复杂布局能力差,需要不同布局嵌套使用。 + 布局嵌套层级高。不同布局的嵌套使用,导致布局的嵌套层级偏高。 + 页面性能低。较高的嵌套层级,需要更多的计算布局时间,降低了页面性能。 正是由于目前布局容器存在的问题,我们需要寻找一种可以解决这些问题的布局容器。正好,ConstraintLayout可以。 ### 二、ConstraintLayout是什么 ConstraintLayout,中文称约束布局,在2016年Google I/O大会时提出,2017年2月发布正式版,目前稳定版本为1.0.2。约束布局作为Google今后主推的布局样式,可以完全替代其他布局,降低页面布局层级,提升页面渲染性能。 ### 三、怎么用ConstraintLayout #### 3.1 环境搭建 ConstraintLayout支持最低Android Studio版本是2.2,但是有些属性在2.2的布局编辑器上不支持编辑,如比例和baseline等约束。所以推荐使用2.3的版本,当然3.0的版本那就更好了。要使用ConstraintLayout,需要在项目中进行如下配置: + 在项目外层定义google maven仓库 ``` repositories { maven { url 'https://maven.google.com' } } ``` + 在要使用ConstraintLayout的module的build.gradle文件中引入约束布局库 ``` dependencies { compile 'com.android.support.constraint:constraint-layout:1.0.2' } ``` #### 3.2 布局引入 按照上述配置好环境后,我们就可以在项目中使用ConstraintLayout了。有两种方式使用: 1. layout转换的方式使用 + 首先,打开一个非ConstraintLayout的布局文件,切换到`Design Tab` + 在Component Tree窗口,选中要转换的layout文件根布局,点击右键,然后选择**Convert layout to ConstraintLayout** 2. 直接新建一个layout文件使用 通过如下方式引入约束布局: ``` ``` #### 3.3 属性介绍 ConstraintLayout的布局属性,乍一看有很多,其实可以分为8个部分,下面一一介绍。 ##### 3.3.1 相对位置 ``` layout_constraintLeft_toLeftOf layout_constraintLeft_toRightOf layout_constraintRight_toLeftOf layout_constraintRight_toRightOf layout_constraintTop_toTopOf layout_constraintTop_toBottomOf layout_constraintBottom_toTopOf layout_constraintBottom_toBottomOf layout_constraintBaseline_toBaselineOf layout_constraintStart_toEndOf layout_constraintStart_toStartOf layout_constraintEnd_toStartOf layout_constraintEnd_toEndOf ``` 以上这些属性,用于设置一个控件相对于其他控件、Guideline或者父容器的位置。以`layout_constraintLeft_toLeftOf`为例,其中`layout_`部分是固定格式,主要的信息包含在下面两部分: + constraintXXX:指定当前控件需要设置约束的属性部分。如`constraintLeft`表示对当前控件的**左边**进行约束设置。 + toXXXOf:其指定的内容是作为当前控件设置约束需要依赖的控件或父容器(可以理解为设置约束的参照物)。并通过`XXX`指定被依赖对象用于参考的属性。如`toLeftOf="parent"` :表示当前控件相对于父容器的左边进行约束设置。 ConstraintLayout的相对位置布局比较灵活,相比于RelativeLayout,ConstraintLayout可以通过`layout_constraintBaseline_toBaselineOf`设置两个控件之间的文字相对于baseline对齐。一个布局效果的例子,如下所示: ```