可能你觉得 ConstraintLayout 属性多,且属性长而弃用它,那你错失了这个大宝贝。
因为在复杂布局,我们会一直用 RelativeLayout 和 LinearLayout 去嵌套,因为嵌套的 ViewGroup 会导致手机多次测量和绘制,从而影响性能,如果嵌套严重可能出现掉帧或卡顿。
使用 ConstraintLayout 一招入魂。一句话概括是:传统布局能实现的,它能轻松实现实现。传统布局不能实现的,它也能实现。
这里举个 2 个简单的例子。
如图下图所示,我们分别用 RelativeLayout 和 ConstraintLayout 去实现它:
<RelativeLayout...>
<TextView
android:id="@+id/txt_a"
android:layout_centerHorizontal="true"
.../>
<RelativeLayout
android:layout_alignTop="@+id/txt_a"
android:layout_toLeftOf="@+id/txt_a"
android:layout_alignBottom="@+id/txt_a"
...>
<TextView
android:layout_centerInParent="true"
android:id="@+id/txt_b"
.../>
</RelativeLayout>
</RelativeLayout>
这里使用了伪代码,把无关紧要的属性去掉了。相信懂的人都明白。这里用图层表示下,如下:
那么接下来看看 ConstraintLayout 如何实现?
<androidx.constraintlayout.widget.ConstraintLayout...>
<TextView
android:id="@+id/txt_a"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
.../>
<TextView
app:layout_constraintRight_toLeftOf="@+id/txt_a"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="@+id/txt_a"
app:layout_constraintBottom_toBottomOf="@+id/txt_a"
android:id="@+id/txt_b"
.../>
</androidx.constraintlayout.widget.ConstraintLayout>
我们继续看下,他的图层关系,真的简洁。
如图下图所示,我们分别用 RelativeLayout 和 ConstraintLayout 去实现它: