ConstraintLayout是Android推出的一个布局,其性能好,官方极力推荐使用ConstraintLayout来编写布局。其中文名字为约束布局,ConstraintLayout和RelativeLayout似乎有很多相似的地方,但是ConstraintLayout更灵活,在适应屏幕大小变化方面更有优势。官方文档中的说法是“ Constraint Layout的所有功能都可以直接从Layout Editor的可视化工具获得,因为layout API和Layout Editor是专门为彼此构建的。 因此,您可以通过拖放而不是编辑XML来完全使用约束布局来构建布局。 ”

或许有些人会想,RelativeLayout已经很香了,为什么还要使用ConstraintLayout呢?

我们都知道,在布局嵌套过多时就会出现一些性能问题。之前我们可以去通过RelativeLayout或者GridLayout来减少这种布局嵌套的问题。现在,我们可以改用ConstraintLayout来减少布局的层级结构。ConstraintLayout相比RelativeLayout,其性能更好,也更容易使用。

约束布局,约束的布局,那么在这里面,约束指的是什么呢?

约束是此布局的基本构建块。 它将一个窗口小部件的定位点与另一个窗口小部件或父窗口小部件连接起来。 有多种约束条件可以操纵以创建响应式UI,它也可以更好地适应不同的屏幕尺寸。

在约束布局中,确定view的位置,至少需要一个水平和垂直约束

app:layout_constraintBottom_toBottomOf="parent"

app:layout_constraintEnd_toEndOf="parent"

app:layout_constraintStart_toStartOf="parent"

app:layout_constraintTop_toTopOf="parent"

这样便得到一个垂直与水平居中的布局

而约束布局中这样的写法有哪些呢?

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

这些属性的值,可以是parent也可以是某个组件的id,也就是说,约束可以基于整体布局,也可以居于某个组件进行约束

而约束于垂直和水平后的位置,则可以使用

app:layout_constraintVertical_bias="0.68"

app:layout_constraintHorizontal_bias="0.3"

来进行调节,数值为0~1

整体使用起来的感觉就是,真香

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐