为什么推荐使用ConstraintLayout
从Android Studio 2.3版本开始,创建Activity时的默认布局容器变为ConstraintLayout。为什么官方推荐使用ConstraintLayout呢?总结一下,主要有下面这三个原因:
减少布局层次。我们知道一个好的布局是浅而宽的,而不是窄而深的。布局层次越浅,即布局层次越少,那么UI测量和布局阶段所花费的时间就越少,UI的性能就越好。通常情况下,我们在使用传统布局容器来实现一些稍微复杂的页面时布局层次很容易就大于等于两层。ConstraintLayout支持构建复杂的页面布局,如果使用它作为页面的布局容器,基本上一层就足够了。
性能较好。Google的工程师测量过ConstraintLayout和RelativeLayout的性能,测量结果表明:ConstraintLayout在测量/布局阶段的性能比RelativeLayout大约高40%。
扩展性好。ConstraintLayout功能强大,当页面的需求发生变化时很方便进行修改和扩展。
准备工作
要在项目中使用ConstraintLayout,需要在模块的build.gradle文件中添加如下依赖:
dependencies {
...
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
}
如果项目还没有使用AndroidX,那么添加如下依赖:
dependencies {
...
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
}
二、相对定位 (Relative positioning)
属性列表:
layout_constraintLeft_toLeftOf
layout_constraintLeft_toRightOf
layout_constraintRight_toLeftOf
layout_constraintRight_toRightOf
layout_constraintTop_toTopOf
layout_constraintTop_toBottomOf
layout_constraintBottom_toTopOf
layout_constraintBottom_toBottomOf
layout_constraintBaseline_toBaselineOf
layout_constraintStart_toEndOf
layout_constraintStart_toStartOf
layout_constraintEnd_toStartOf
layout_constraintEnd_toEndOf
看一张官方的图,很好理解
这里写图片描述
这里就不一一解释了,拿 layout_constraintLeft_toRightOf来简单介绍一下:
假如有一个控件 button1 使用 layout_constraintLeft_toRightOf = “@+id/button2” 意思就是button1左边约束于button2的右边(在控件上可以看到button1左边有一条约束线连到button2右边),也可以理解成相对布局的toRightof。
三、边距(Margins)
有以下属性:
android:layout_marginStart
android:layout_marginEnd
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom
使用方法就不多介绍了,注意一点,Margins的值必须是非负的 Dimension( 尺寸值 )
这里主要介绍 (Margins when connected to a GONE widget),当你对一个 visibility 是View.GONE的控件使用Margin的时候。首先属性有:
layout_goneMarginStart
layout_goneMarginEnd
layout_goneMarginLeft
layout_goneMarginTop
layout_goneMarginRight
layout_goneMarginBottom
一般这些属性是与上面的Margin正常属性一起使用的,或者说这些属性就是为了防止当你Margin连接的那个控件GONE的时候出现预料之外的事情。
总结一下:其实这些属性就是配合正常的Margin设置属性一起使用,防止某个控件GONE之后影响布局。单独用的话没有意义。
还有一点,一个控件GONE之后,并不是直接从布局完全消失。从上面的设计图中其实可以看出,GONE之后该控件只是(类似)缩成一个点了,当然margin也是会消失的(这个时候就使用Gonemargin就可以实现间距)
app:layout_goneMarginStart="40dp" 使用这个属性时,如果约束控件 没有gone 就不显示该距离,如果约束控件gone了,那么 就会出现 这个40的 间距
四、偏向(Bias)
Bias有以下两个属性:
- layout_constraintHorizontal_bias
- layout_constraintVertical_bias
这个TextView有下面几条属性:
app:layout_constraintBottom_toBottomOf=“parent”
app:layout_constraintEnd_toEndOf=“parent”
app:layout_constraintStart_toStartOf=“parent”
app:layout_constraintTop_toTopOf=“parent”
这其实是矛盾的,控件左边约束于parent,右边也是约束于parent,那到底是靠左边还是右边呢,上面已经有答案了。我哪也不靠。
这种情况默认会变成bias,而且默认不写bias的两个属性意味着都等于0.5 即不偏向任何一边,居中。
现在我给它加上bias属性
app:layout_constraintHorizontal_bias=“0.1”
app:layout_constraintVertical_bias=“0.05”
总结: Bias当控件两边(上下或者左右)都有约束的时候,默认为bias约束,可以使用bias的两个属性来控制偏向哪边。