1.介绍
约束布局ConstraintLayout
本身就是一个ViewGroup,它用来解决布局嵌套过多的问题(嵌套越多,绘制消耗的时间越长),以灵活的方式定位/调整小部件(API 9以上均可使用),相比RelativeLayout更灵活,性能更加的出色,更好的适配屏幕大小不同的机型。Android Studio 2.3开始默认创建Activity是都是使用它。
2.使用
使用它也非常的简单,高版本的AS通常都会自动的添加它的依赖,如果未添加依赖在app/build.gradle中添加相应的依赖即可。
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
2.1 相对定位
即一个组件相对于另一个组件的约束,非常的好理解(与RelativeLayout非常的类似)。
例:要实现B在A的右侧:
按钮A在按钮B的右侧,也可以理解为按钮B的左侧位于按钮A的右侧;其他的方位都一样。我们在代码中的表示如下:
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:id="@+id/btn2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
app:layout_constraintLeft_toRightOf="@id/btn1" />
其中最关键的属性为app:layout_constraintLeft_toRightOf="@id/btn1"
,代表按钮B的左侧位于按钮A的右侧
其中常用的属性还有:
// 值可以为parent,意思就是A的左侧位于父布局的左侧(top_top|bottom_bottom等一样)
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_constraintBaseline_toBaselineOf
,如图所示,两个Button的高度不一致,但是又希望他们文本对齐,这个时候就可以使用layout_constraintBaseline_toBaselineOf
保证文字相对齐:
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="Button3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.3"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:text="Button4"
app:layout_constraintBaseline_toBaselineOf="@id/btn3"
app:layout_constraintLeft_toRightOf="@id/btn3" />
2.2 角度定位
角度定位指的是利用角度以及距离决定某些控件中心点的坐标。
三个属性为:
app:layout_constraintCircle="@id/btn3"
指定相对于哪个控件app:layout_constraintCircleAngle="160"
角度app:layout_constraintCircleRadius="150dp"
中心点的距离
其中的关系如下图所示:
例子:按钮5在按钮3的160度方向距离为150dp
<Button
android:id="@+id/btn3"
android:layout_width="wrap_content"
android:layout_height="100dp"
android:text="Button3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.3"