ConstraintLayout(约束布局)的出现是为了在Android应用布局中保持扁平的层次结构,减少布局的嵌套,为应用创建响应快速而灵敏的界面。ConstraintLayout可以替代其他布局。
implementation'com.android.support.constraint:constraint-layout:1.1.2'
ConstraintLayout具有RelativeLayout的能力,可以将一个控件置于相对于另一个控件的位置。
示例:将B按钮放在A按钮的右边
<Buttonandroid:id="@+id/buttonA".../>
<Buttonandroid:id="@+id/buttonB"...
app:layout_constraintLeft_toRightOf="@+id/buttonA"/><!--B控件的左边与A控件右边对齐-->
控件的边界名:
其他相关属性
这些属性会引用另一个控件的id
或者parent
(这会引用父容器,即ConstraintLayout)
<Buttonandroid:id="@+id/buttonB"...
app:layout_constraintLeft_toLeftOf="parent"/>
在ConstraintLayout中,layout_margin及其子属性的作用都被复写,margin属性只对其相约束的View起作用。
示例1:有约束属性
示例2:没有约束属性,margin就会失效
当被约束的目标对象的可见性为
View.GONE
,可以使用gone margin
来设置,它只会在目标Target为GONE
的时候生效。
相关属性:
示例1:
示例2:
在ConstraintLayout中没有直接的属性让一个控件水平居中,或者竖直居中,可以使用如下方式:
如果想要将控件在水平方向偏向左、或者在竖直方向偏向一个方向,就可以配合使用bias
属性:
居中情况下,bias的默认值为0.5,取值范围是
0~1
,是以left或top为始起边界。
示例:
可以使用角度和距离来约束一个控件相对于另一个控件的位置。
相关属性:
示例:
ConstraintLayout中有3中方式来设置子View的宽高尺寸:
MATCH_CONSTRAINT
,ConstraintLayout不推荐使用示例1:0dp的使用,可以看到,View的宽度就是父容器的宽度
示例2:B按钮被拉伸
当控件的尺寸被设置为MATCH_CONSTRAINT
时,默认情况下尺寸会被设置成占用所有可用空间,可用使用下面几个属性进行约束:
如果一个View的尺寸被设置为
wrap_content
,那么当View的内容太多时,可能会超出约束规定的范围,约束布局提供了两个属性来限制View的尺寸:
示例1:默认情况下,B控件由于内容较多,高度超出了约束规定的范围。
示例2:限制高度
使用百分比步骤
MATCH_CONSTRAINT
(0dp)layout_constraintWidth_percent
或layout_constraintHeight_percent
,值为0~1
示例:
ConstrainLayout提供了
ratio
属性,用来限制View的宽高比例。 使用Ratio
属性,宽高两个尺寸中至少要一个是MATCH_CONSTRAINT
(0dp) 默认情况下,1:2,表示宽:高,宽为1,高为2 宽高都为MATCH_CONSTRAINT
时,可以在比例前加W或者H:W,1:2
:表示宽=2,高=1,即H:W = 1:2H,1:2
:表示高=2,宽=1,即W:H = 1:2
示例1:2:1
示例2:H,16:9(宽度占满父控件,约束高度为宽的9/16)
示例2:W,1:5(高度占满父控件,宽度为高度的1/5)
示例3:指定宽度为屏幕一半,并保持比例
链使我们能够对一组在水平或竖直方向互相关联的控件的属性进行统一管理。 成为链条的条件: 一组控件它们通过一个双向的约束关系链接起来,并且链的属性由一条链的头结点控制。
示例:
设定链条样式的属性:
链的样式:
权重链,宽或高需要设置为
MATCH_CONSTRAINT
。 使用layout_constraintHorizontal_weight
或layout_constraintVertical_weight
设置对应的权重
示例:
Guideline,是一个辅助控件,可见性为
GONE
,主要作用是充当一个锚点。
设置Guidline的方向:
设置Guidline的位置:
示例
Barrier,译为屏障,是一个虚拟的辅助控件,用来防止它引用的View的位置超过自己。
相关属性:
示例:
Group,用于控制多个控件的可见性。
Placeholder,占位符,可以用来放置其他View,用这个可以写一些布局模板。
示例:
模板文件:
tools:parentTag:设为ConstraintLayout,使得编辑器将当前merge标签当做约束布局来预览。 content:是要填入这个占位符的View的id。
引用模板: