简介
更加灵活的布局容器,RelativeLayout 进阶版本,当前记录基于2.1.4版本
1.设置相对位置
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
- 对齐的对象可以是
子View的id或者parent - 国际化 RTL 建议使用
start替换left,end替换right - 如果当前布局不需要RTL,可以保留使用
left和right - BaseLine 是基于文字的基线对齐,2个字体大小不一样的TextView会根据文字底部进行对齐处理
2.设置 Margins
android:layout_marginStart
android:layout_marginEnd
android:layout_marginLeft
android:layout_marginTop
android:layout_marginRight
android:layout_marginBottom
layout_marginBaseline
- margins 可以为任意数,负数也可以了
3.对于 GONE 的 View 也可以设置Margins
layout_goneMarginStart
layout_goneMarginEnd
layout_goneMarginLeft
layout_goneMarginTop
layout_goneMarginRight
layout_goneMarginBottom
layout_goneMarginBaseline
- ConstraintLayout 对 GONE 进行了特殊处理,相当于改成了一个像素点的大小,隐藏的时候依然可以保证相对位置,但是大小改变了,设置的时候需要注意下隐藏后的效果。
4.尺寸
WRAP_CONTENT
MATCH_CONSTRAINT (0dp)
MATCH_PARENT
建议使用 MATCH_CONSTRAINT(0dp) 代替 MATCH_PARENT,因为 0dp 也是默认充满全部,但是可以被一些其他属性约束。比如限制最大最小宽度
layout_constraintWidth_max
layout_constraintWidth_min
5.chain
可以设置多个View同时居中显示 packed
<TextView
android:id="@+id/tv_title"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintEnd_toStartOf="@+id/tv_title_kotlin"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/tv_title_kotlin"
app:layout_constraintHorizontal_chainStyle="packed"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="@+id/tv_title"
app:layout_goneMarginStart="16dp" />
资料
ConstraintLayout
使用 ConstraintLayout 构建自适应界面
ConstraintLayout 更新记录
github 地址
解析ConstraintLayout的性能优势
本文介绍了ConstraintLayout的高级用法,包括设置相对位置、Margins、处理GONE的View、尺寸控制以及链式布局。推荐使用MATCH_CONSTRAINT替代MATCH_PARENT,并强调了0dp在约束布局中的灵活性。此外,文章还提到了如何创建居中显示的链式布局和ConstraintLayout的性能优势。
607

被折叠的 条评论
为什么被折叠?



