约束布局 ConstraintLayout 是一个ViewGroup,主要解决布局嵌套过多,从而在布局加载时,就要耗费了许多内存,影响了项目的整体的一个客户体验感,以及屏幕适配。所以约束布局也是项目中,比不可少的部分!
这里有官方文档,帮助大家更详细的去了解一下:
https://developer.android.google.cn/reference/android/support/constraint/ConstraintLayout
手动操作:https://blog.csdn.net/guolin_blog/article/details/53122387
1.第一步添加依赖、布局设置为ConstranitLaoyout:
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
2.相对定位:相对定位在约束布局中是最基本的模块,主要分为横向、纵向的约束关系:
(1)相对定位的属性:
layout_constraintLeft_toLeftOf //控件1的左侧放置到控件2的左边
layout_constraintLeft_toRightOf //控件1的左侧放置到控件2的右边
layout_constraintRight_toLeftOf //控件1的右侧放置到控件2的左边
layout_constraintRight_toRightOf //控件1的右侧放置到控件2的右边
layout_constraintTop_toTopOf //控件1的顶部放置到控件2的顶部
layout_constraintTop_toBottomOf //控件1的顶部放置到控件2的底部
layout_constraintBottom_toTopOf //控件1的底部放置到控件2的顶部
layout_constraintBottom_toBottomOf //控件1的底部放置到控件2的底部
layout_constraintStart_toEndOf //控件1的起始边放置到控件2的尾部
layout_constraintStart_toStartOf //控件1的起始边放置到控件2的起始边
layout_constraintEnd_toStartOf //控件1的尾部放置到控件2的起始边
layout_constraintEnd_toEndOf //控件1的尾部放置到控件2的尾部
//Baseline指的是文本基线,当两个文本高度不同,也可以对齐的方式
layout_constraintBaseline_toBaselineOf
app:layout_constraintCircle="@+id/TextView1"
app:layout_constraintCircleAngle="120"(角度)
app:layout_constraintCircleRadius="150dp"(距离)
3.边距:
ConstraintLayout的边距常用属性如下:
android:layout_marginStart
android:layout_marginEnd
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom
这里注意了控件必须在布局里约束一个相对位置,否则外边距不生效的。
ConstraintLayout的Gone margin常用属性如下:
layout_goneMarginStart
layout_goneMarginEnd
layout_goneMarginLeft
layout_goneMarginTop
layout_goneMarginRight
layout_goneMarginBottom
4.居中和倾向
一般我们在其他布局当中只需要把layout_centerInParent设为true即可,那么在约束布局当中需要在两个控件之间添加约束
ConstraintLayout的居中常用属性如下:
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"