ConstraintLayout 翻译为 约束布局,也有人把它称作 增强型的相对布局,由 2016 年 Google I/O 推出。扁平式的布局方式,无任何嵌套,减少布局的层级,优化渲染性能。从支持力度而言,将成为主流布局样式,完全代替其他布局。
1、和相对布局的对比
但既然是增强型的相对布局,自然会同相对布局一起进行比较。这篇文章是ConstraintLayout的主场,自然以ConstraintLayout的布局属性为比较基准:
- layout_constraintLeft_toLeftOf 和RelativeLayout中的android:layout_alignLeft 功能一样,控件的左边缘与给定ID的左边缘对齐。
- layout_constraintLeft_toRightOf和RelativeLayout中的android:layout_toRightOf 功能一样,控件的左边缘与给定ID的控件右边缘对齐。
- layout_constraintRight_toLeftOf和RelativeLayout中的android:layout_toLeftOf 功能一样,控件的右边缘与给定ID的控件左边缘对齐。
- layout_constraintRight_toRightOf和RelativeLayout中的android:layout_alignRight 功能一样,控件的右边缘与给定ID的右边缘对齐。
- layout_constraintTop_toTopOf和RelativeLayout中的android:layout_alignTop 功能一样,控件的顶部边缘与给定ID的顶部边缘对齐。
- layout_constraintTop_toBottomOf和RelativeLayout中的android:layout_below功能一样,控件的底部置于给定ID的控件之下。
- layout_constraintBottom_toTopOf和RelativeLayout中的android:layout_above能一样,控件的底部置于给定ID的控件之上。
- layout_constraintBottom_toBottomOf和RelativeLayout中的android:layout_alignBottom 能一样,控件的底部边缘与给定ID的底部边缘对齐。
2、比相对布局减少的部分 - android:layout_alignParentTop控件的顶部与父控件的顶部对齐,在约束布局中用layout_constraintTop_toTopOf(parent)实现
- android:layout_alignParentBottom 控件的底部与父控件的底部对齐,在约束布局中用layout_constraintBottom_toBottomOf(parent)实现
- android:layout_alignParentLeft 控件的左部与父控件的左部对齐,在约束布局中用layout_constraintLeft_toLeftOf(parent)实现
- android:layout_alignParentRight 控件的右部与父控件的右部对齐,在约束布局中用layout_constraintRight_toRightOf(parent)实现
- android:layout_centerInParent水平垂直居中,在约束布局中用app:layout_constraintBottom_toBottomOf=“parent”
app:layout_constraintTop_toTopOf=“parent” />
app:layout_constraintLeft_toLeftOf=“parent”
app:layout_constraintRight_toRightOf=“parent” - android:layout_centerHorizontal 水平居中,在约束布局中用 app:layout_constraintLeft_toLeftOf=“parent”
app:layout_constraintRight_toRightOf=“parent” - android:layout_centerVertical 垂直居中,在约束布局中用app:layout_constraintBottom_toTopOf=“parent” app:layout_constraintTop_toBottomOf=“parent”
ConstraintLayout实现了语法上的统一,语法的统一又促进了布局算法的统一,从而提高了布局效率。同样的功能,约束布局的描述更接近于算法,相对布局的描述更符合普通人的思维。
3、比相对布局增强的部分 - layout_constraintBaseline_toBaselineOf文本基线
- layout_constraintStart_toEndOf 控件的开始位置与给定ID的控件结束位置对齐,属于位置定位,没有控件之间的默认间距。而layout_constraintLeft_toRightOf是位置排版,有间距。
- layout_constraintStart_toStartOf 控件的开始位置与给定ID的控件开始位置对齐,属于位置定位。
- layout_constraintEnd_toStartOf 控件的结束位置与给定ID的控件开始位置对齐,属于位置定位,没有控件之间的默认间距。
- layout_constraintEnd_toEndOf 控件的结束位置与给定ID的控件结束位置对齐,属于位置定位。
- Barrier 在约束布局中,可以使用属性constraint_referenced_ids属性来引用多个带约束的组件,从而将它们看作一个整体
- Group 用于控制多个控件的可见性
- Guideline是只能用在ConstraintLayout布局里面的一个工具类,用于辅助布局,类似为辅助线,本身是不显示的。可以设置android:orientation属性来确定是横向的还是纵向的