什么是ConstraintLayout?
ConstraintLayout是在android Studio2.2更新中推出的一个新功能,也是I/O大会上重点解说的一个新特性。在升级的2.3之后项目中创建xml默认就是使用了ConstraintLayout,说明ConstraintLayout确实有让谷歌认可的独到之处。
特点
扁平化布局,减少布局层级,提高GPU的渲染速度,提升应用使用中的流畅度,提高开发效率
案例
这是一个布局效果图,同时用普通布局和ConstraintLayout来实现,对比下效果。

使用传统布局来构建,XML 文件会包含类似于下面这样的元素层次结构
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| <RelativeLayout> <ImageView /> <ImageView /> <RelativeLayout> <TextView /> <LinearLayout> <TextView /> <RelativeLayout> <EditText /> </RelativeLayout> </LinearLayout> <LinearLayout> <TextView /> <RelativeLayout> <EditText /> </RelativeLayout> </LinearLayout> <TextView /> </RelativeLayout> <LinearLayout > <Button /> <Button /> </LinearLayout> </RelativeLayout>
|
使用 ConstraintLayout 来构建相同的布局,XML 文件会包含类似于下面这样的元素层次结构:
1 2 3 4 5 6 7 8 9 10 11 12
| <android.support.constraint.ConstraintLayout> <ImageView /> <ImageView /> <TextView /> <EditText /> <TextView /> <TextView /> <EditText /> <Button /> <Button /> <TextView /> </android.support.constraint.ConstraintLayout>
|
从层级上可以看出ConstraintLayout实现了扁平化,没有多余的嵌套,在View的底层实现上少了很多次 测量 布局绘制,大大提高了界面的渲染速度
通过性能分析工具得到的结果,ConstraintLayout 在测量/布局阶段的性能比 RelativeLayout大约高 40%。

Inspector
Guidelines
自动添加约束
解析ConstraintLayout的性能优势
开始使用ConstraintLayou