概述约束布局的优势:
从开发者的使用上来说:约束布局就是一个强力升级版的RelativeLayout,RelativeLayout能实现的ConstraintLayout也能实现,RelativeLayout不能实现的ConstraintLayout也能实现。
从性能上来说:使用ConstraintLayout的布局基本上不存在ViewGroup的多层级嵌套,我们知道View的绘制是从顶层开始,以遍历的形式完成整个界面的measure(尺寸)、layout(布局)、draw(绘制)。所以在复杂布局的绘制上ConstraintLayout具有一定的性能优势。
a 可视化界面编辑
b 可减少界面层级嵌套,尽量扁平化
c 控件可以进行相对定位,有RelativeLayout和LinearLayout的优点
局限性:
控件的大小控制和RelativeLayout、LinearLayout一样,没法做到不同分辨率下的自适配,只能实现控件间相对关系比较舒服的适配。
1.0版本以后可以做到控件大小根据父控件进行百分比适配了。
2、引入
build.gradle中引入依赖:
implementation 'androidx.constraintlayout:constraintlayout:2.0.1'
之后在布局文件中就可以引入ConstraintLayout使用了。
3、相对布局属性
最基础的Constraint属性,可以设置在父控件内的位置,相对其他控件的相对位置,layout_constraintLeft_toLeftOf //同向左对齐
layout_constraintRight_toRightOf //同向右对齐
layout_constraintTop_toTopOf //同向顶对齐
layout_constraintBottom_toBottomOf //同向底对齐
//start=left end=right
layout_constraintRight_toLeftOf //相邻,在其左边
layout_constraintLeft_toRightOf //相邻,在其右边
layout_constraintTop_toBottomOf //相邻,在其底部
layout_constraintBottom_toTopOf //相邻,在其顶部
layout_constraintBaseline_toBaselineOf //基线对齐
4、百分比属性
可以设置占父控件的百分比layout_constrainWidth_percent
ayout_constrainHeight_percent
5、链条样式
-
spread - 元素将被展开(默认样式)
-
加权链 - 在spread模式下,如果某些小部件设置为MATCH_CONSTRAINT,则它们将拆分可用空间
-
spread_inside - 类似,但链的端点将不会扩展
-
packed - 链的元素将被打包在一起。 孩子的水平或垂直偏差属性将影响包装元素的定位app:layout_constraintHorizontal_chainStyle="spread"
6、倾向bias
搭配bias,能使约束偏向某一边,默认是0.5,有以下属性:
-
layout_constraintHorizontal_bias (0最左边 1最右边)
-
layout_constraintVertical_bias (0最上边 1 最底边)
利用该属性可以实现相对布局按一定百分比分布。