1.约束布局ConstraintLayout
约束布局具有很好的性能优势,可以绘制扁平化界面,使用一层嵌套便可以实现界面,减少复杂界面造成的布局嵌入过深的问题。
使用该布局,需要引入依赖implementation ‘androidx.constraintlayout:constraintlayout:2.1.2’
使用最新的Android studio新建一个布局文件时,google已经默认设置父布局为ConstraintLayout。
2.在布局文件中使用约束布局
①位置约束layout_constraintXXX_toYYYOf
设置ConstraintLayout的位置约束属性时,属性值可以是parent或者@+id/兄弟组件的id:
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_constraintXXX_toYYYOf,在Android中组件都是矩形的,矩形都会有四条边,上Top 下 Bottom 左Left(Start)右Right(End),其中XXX代表当前组件的某一条边,YYY代表约束XXX的parent或兄弟组件的某一条边。当XXX和YYY代表的边相同时,表示两条边对齐;当XXX和YYY代表的边相反时,表示一条边在另一条边的一侧。
例如:
layout_constraintLeft_toLeftOf=“parent” 代表当前组件的左边和父组件的左边对齐。
layout_constraintLeft_toRightOf="@+id/tvUserName" 代表当前组件的左边在id是tvUserName兄弟组件的右边,也就是当前组件在tvUserName的右边。
注意:竖直方向(Top、Bottom)和水平方向(Left、Right)必须完成约束,因为要确定一个组件的位置,必须知道它水平方向和竖直方向的位置。
②文字基线对齐layout_constraintBaseline_toBaselineOf
layout_constraintBaseline_toBaselineOf可以让两个文本的基线对齐
③居中和bias百分比偏移
1)父布局水平居中:
如果设置app:layout_constraintLeft_toLeftOf=“parent”,则view会贴着父view的左边,设置app:layout_constraintRight_toRightOf="parent"则会贴着右边,如果两个都设置那么当前组件就会在父布局中水平居中。
2)父布局竖直居中:同理,如果同时设置app:layout_constraintBottom_toBottomOf=“parent”和app:layout_constraintTop_toTopOf="parent",那么当前组件就会在父布局中竖直居中。
3)父布局水平和竖直同时居中:同时设置
app:layout_constraintLeft_toLeftOf=“parent”
app:layout_constraintRight_toRightOf=“parent”
app:layout_constraintTop_toTopOf=“parent”
app:layout_constraintBottom_toBottomOf=“parent”
4)约束范围内居中:从上面可以看出,如果给当前组件两边(水平方向或竖直方向)都加一个约束条件,在无法确定倾向哪边的情况下,组件就会居中。所以上面三个居中同样可以把属性值parent换成兄弟组件的id,那么当前组件在约束范围内就会居中显示。
5)百分比偏移: 如果想让当前组件向左偏一些,比如位于父布局的1/3处,就需要使用如下属性:layout_constraintHorizontal_bias,表示属性值偏移量,取值范围从0~1,0即挨着左边,1是挨着右边,所以要让当前组件位于父布局的1/3处,应该设置app:layout_constraintHorizontal_bias=“0.3”,效果如下:
实际上,bias值=当前View左约束的长度/(当前View左约束的长度+当前View右约束的长度),默认值为0.5(所以默认居中)。
当设置app:layout_constraintHorizontal_bias=“1”时,左约束长度占据了所有的约束长度,效果如下:
④角度约束
ConstraintLayout可以轻松实现一个控件在另一个控件的某个角度的某个位置。用到的属性为:
layout_constraintCircle 角度中心组件的id
layout_constraintCircleAngle 角度(0-360)
layout_constraintCircleRadius 到中心的距离
例如:tvUserSex在tvUserName的45度方向,距离为100dp:
<TextView
android:id="@+id/tvUserName"
…
android:text="用户名称"/>
<TextView
android:id="@+id/tvUserS