简介
为什么要使用ConstraintLayout?
- 为了在Android应用布局中保持扁平的层次结构,减少布局的嵌套
- 为应用创建响应快速而灵敏的界面
- 使用比RelativeLayout更灵活,性能更出色
- 可以按照比例约束控件位置和尺寸,能够更好地适配屏幕大小不同的机型
既然ConstraintLayout的优点这么大,但是它的缺点我们也一点要了解,才能在开发中更加灵活的运用。缺点:
- 删除某个控件会引起其他关联此id控件都收到影响
导入依赖
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
布局属性
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
使用:
app:layout_constraintBaseline_toBaselineOf="@+id/tv_1"
居中
<!--水平居中-->
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
<!--垂直居中-->
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
一行3个控件居中
<TextView
android:id="@+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/TextView2" />
<TextView
android:id="@+id/TextView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toRightOf="@+id/TextView1"
app:layout_constraintRight_toLeftOf="@+id/TextView3"
app:layout_constraintRight_toRightOf="parent" />
<TextView
android:id="@+id/TextView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintLeft_toRightOf="@+id/TextView2"
app:layout_constraintRight_toRightOf="parent" />
3个TextView相互约束,两端两个TextView分别与parent约束,成为一条链
在某个控件右边
app:layout_constraintLeft_toRightOf="@+id/TextView1"
在某个控件下面
app:layout_constraintTop_toBottomOf="@+id/TextView1"
两个居中的控件贴合一起
app:layout_constraintHorizontal_chainStyle="packed":将两个控件水平排列,并将它们紧密地包装在一起。
app:layout_constraintVertical_chainStyle="packed":将两个控件垂直排列,并将它们紧密地包装在一起。
app:layout_constraintHorizontal_bias="0":将第一个控件的左边缘与父布局的左边缘对齐。
app:layout_constraintVertical_bias="0":将第一个控件的顶部边缘与父布局的顶部边缘对齐。