简介
ConstraintLayout(即约束布局)发布于2016年Google I/O大会。布局嵌套过多有性能问题,RelativeLayout或GridLayout可减布局嵌套,现可用ConstraintLayout减布局层级结构。相比RelativeLayout性能更好且更易用,结合Android Studio布局编辑器可实现拖拽控件编写布局等等。
资料
- 使用 ConstraintLayout 设计您的 Android 视图
- Android新特性介绍,ConstraintLayout完全解析
- 约束布局ConstraintLayout看这一篇就够了
- 实战篇ConstraintLayout的崛起之路
依赖
新建工程Android Studio默添ConstraintLayout依赖。改旧工程于build.gradle添:
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
属性
位置
layout_constraintLeft_toLeftOf
约束左于某控件左
layout_constraintLeft_toRightOf
约束左于某控件右
layout_constraintRight_toLeftOf
约束右于某控件左
layout_constraintRight_toRightOf
约束右于某控件右
layout_constraintTop_toBottomOf
约束上于某控件下
layout_constraintBottom_toTopOf
约束下于某控件上
layout_constraintBottom_toBottomOf
约束下于某控件下
layout_constraintStart_toEndOf
约束开始于某控件结束
layout_constraintStart_toStartOf
约束开始于某控件开始
layout_constraintEnd_toStartOf
约束结束于某控件开始
layout_constraintEnd_toEndOf
约束结束于某控件结束
layout_constraintBaseline_toBaselineOf
MATCH_PARENT
官网
Important: MATCH_PARENT is not supported for widgets contained in a ConstraintLayout, though similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to "parent".
ConstraintLayout不支持MATCH_PARENT,可通MATCH_CONSTRAINT配合约束实现类似效果。
使用
居中
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
缺点
调布局特别删控件时依赖关系较多则麻烦。Google建用ConstraintLayout替RelativeLayout。