同学们,先来个小调查
约束布局-Constraint Layout
What is this?
Constraint 美[k?n?strent] 约束
减少多层嵌套布局
尽可能的使布局 宽而短,而不是 窄而长
简单来说,她是相对布局的升级版本,但是区别与相对布局更加强调约束。何为约束,即控件之间的关系。
她能让你的布局更加扁平化,一般来说一个界面一层就够了;同时借助于AS我们能极其简单的完成界面布局。
一些分析
对于单层的布局,LinearLayouts表现出更加优秀的性能
RelativeLayouts经常需要measure所有子节点两次才能把子节点合理的布局。如果子节点设置了weights属性,LinearLayouts也需要measure这些节点两次,才能获得精确的展示尺寸。如果LinearLayouts或者RelativeLayouts被套嵌使用,measure所费时间可能会呈指数级增长(两个套嵌的views会有四次measure,三个套嵌的views会有8次的measure)
性能对比-耗时
测试用例:布局层级为1层
LinearLayout: 2.637(measuer 0.486 layout 0.093 draw 2.058)
RelativeLayout : 10.4071ms(measuer 1.3661 layout 0.227 draw 8.814)
ConstraintLayout : 13.128ms.(measuer 6.742 layout 0.201 draw 6.185)
测试用例:布局层级为4个View(2层)
LinearLayout : 2.46 (measuer 0.125 layout 0.085 draw 2.25)
RelativeLayout : 2.632(measuer 0.184 layout 0.072 draw 2.376)
ConstraintLayout : 3.634(measuer 1.264 layout 0.103 draw 2.267)
测试用例:布局层级为3/4层
LinearLayout & FrameLayout : 3.006ms
RelativeLayout : 2.8914ms
ConstraintLayout : 2.606ms
安卓布局层级性能对比
约束布局的属性
常用属性
中间对齐
百分比bias
Chain链式结构
基准线Guidelines
Ratio比例大小属性
开发过程中的注意事项
layout_marginLeft和layout_marginRight不起作用: 当一个控件左右都约束了parent,可能会遇到左右间隔不起作用的情况,原因是android:layout_width设置了match_parent或者wrap_content,需要改为0dp变成Match Constraint才会起作用。
布局优化
删除不必要的background
减少嵌套层级,选用合理的方式
使用merge
“ Enjoy your coding time!欢迎喜欢安卓开发的同学关注我,会有更多技术文章跟大家分享 ”