本文参考:https://juejin.im/post/59c13be46fb9a00a496e5ad1
1.ConstraintLayout定义
Constraint Layout是Google在2016年的Google I/O大会上提出的一个可以灵活控制子控件的位置和大小的新布局。并且其号称可以实现布局最大程度的扁平化。
2.ConstraintLayout优点
1.Constraint Layout可以在不嵌套view group的情况下实现非常庞大、复杂的布局。实现扁平化。
2.Constraint Layout同时具有Relative Layout和Linear Layout的优点、特性。功能强大。
3.使用Constraint Layout来布局时性能要比其他布局方式高。
4.Constraint Layout无论是通过布局管理器拖拽,鼠标控制的形式实现还是使用XML代码去写,都比较方便。
3.ConstraintLayout使用
在app的gralde文件下添加如下代码即可使用:
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
4.ConstraintLayout简介
要在 ConstraintLayout 中定义 View 的位置,必须为该 View 添加至少一个水平和垂直约束(否则该 View 就会在左上角绘制)。该约束对象可以是另一个视图,或者父布局(也就是 ConstraintLayout),或者是不可见的 Guideline,否则编译器会报错。
约束布局中的控件操作可以使用图形化界面完成,但是这样太简单了而且不能精细化操作,所以本文主要用代码使用ConstraintLayout。
在XML文件中添加一个约束布局。
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.constraint.ConstraintLayout>
4.1 Relative positioning
约束的效果和RelativeLayout布局有异曲同工之处,只不过要比RelativeLayout强大。约束能允许我们指定一个控件相对于另一个控件的位置,通过一些属性我们可以对组件进行水平或者垂直排列。例如当我们使用含有Left, Right, Start 或者End关键词词属性进行定位时即是对组件进行水平方向排列,同理 top, bottom 和 text baseline(文字的基线位置)就是垂直方向排列。具体相对定位的一些属性组合如下
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 当前组件的结束与某组件的结束对齐
对于上面这些属性的值有两种,一种就是同层级组件ID,还有就是parent,当值为parent时即是相对于父布局进行定位。
将一个控件放在视图的中间,这个可以理解从四个方向都又拉力,把这个控件拉到了中间。
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf