一、介绍配置
约束布局ConstraintLayout 是一个ViewGroup,可以在Api9以上的Android系统使用它,它的出现主要是为了解决布局嵌套过多的问题,以灵活的方式定位和调整小部件。从 Android Studio 2.3 起,官方的模板默认使用 ConstraintLayout。
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
官方文档:https://developer.android.google.cn/reference/android/support/constraint/ConstraintLayout
二、使用
2.1 相对定位
常用属性:
layout_constraintLeft_toLeftOf :当前view的右侧和另一个view的右侧位置对齐,与RelativeLayout的alignLeft属性相似
layout_constraintTop_toTopOf
layout_constraintRight_toRightOf
layout_constraintBottom_toBottomOf
layout_constraintEnd_toEndOfL
layout_constraintStart_toStartOf :同Left_toLeftOf
layout_constraintLeft_toRightOf:当前view的左侧约束条件为位于另一个view的右侧,与RelativeLayout的toRightOf属性相似
layout_constraintRight_toLeftOf
layout_constraintTop_toBottomOf
layout_constraintBottom_toTopOf
layout_constraintStart_toEndOf:同Left_toRightOf
layout_constraintEnd_toStartOf
layout_constraintBaseline_toBaselineOf
注意:
- 容器里面的控件如果设置了左右约束,将不支持设置match_parent 改用0dp代替
- 代替属性Important: MATCH_PARENT is not supported for widgets contained in a ConstraintLayout, though similar behavior can be defined by using MATCH_CONSTRAINT with the corresponding left/right or top/bottom constraints being set to “parent”.`
- Guideline控件在容器里面可以设置wrap_content
layout_constraintBaseline_toBaselineOf : 表示此控件的底部边框与某个控件的底部边框水平对齐或其上边
以下为 TextView的文本基线对齐
<Button
android:id="@+id/text1"
android:layout_height="80dp"
android:text="Text1"
....></Button>
<Button
android:id="@+id/text2"
android:layout_height="wrap_content"
android:text="Text2"
...></Button>
<Button
android:id="@+id/text3"
android:layout_height="80dp"
android:text="Text3"
app:layout_constraintBaseline_toBaselineOf="@+id/text2"
....></Button>
引导线约束Guideline
添加垂直或水平的引导线来约束视图,并且应用用户看不到该引导线。 您可以根据相对于布局边缘的 dp 单位或百分比在布局中定位引导线。
要创建引导线,请点击工具栏中的 Guidelines,然后点击 Add Vertical Guideline 或 Add Horizontal Guideline。
拖动虚线将其重新定位,然后点击引导线边缘的圆圈以切换测量模式。
以下图例为横向guide引导线,定位相对于X轴方向布局边缘30%
<androidx.constrain