RelativeLayout 和 ConstraintLayout

78 阅读1分钟

实现相同的布局

<?xml version="1.0" encoding="utf-8"?>
<com.hsw.medialearn.MyXXX 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"
    tools:context=".FrameActivity">

    <com.hsw.medialearn.MyLinerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:orientation="vertical">
        <com.hsw.medialearn.MyFrameView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <com.hsw.medialearn.MyRelativeView
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <TextView
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:text="123"/>
            </com.hsw.medialearn.MyRelativeView>
        </com.hsw.medialearn.MyFrameView>
    </com.hsw.medialearn.MyLinerView>
</com.hsw.medialearn.MyXXX>

下面把XXX替换为 RelativeLayout ,打印各个view的onMeasure

image.png

然后把XXX替换为 ConstraintLayout ,打印各个view的onMeasure

image.png 对比发现 RelativeLayout 子View 的测量测量次数是 ConstraintLayout 的两倍,当嵌套越深,则测量次数越多。

这个主要是因为 RelativeLayout 的渲染流程:

  1. 执行一次“布局和测量”遍历。在此过程中,框架会根据每个子对象的请求计算该子对象的位置和大小。
  2. 结合此数据和对象的权重确定关联视图的恰当位置。
  3. 执行第二次布局遍历,以最终确定对象的位置。
  4. 进入渲染过程的下一个阶段。

这就所谓的 Double Taxation。

当视图层级只有一层的情况下,使用两者都是可以的,没有差别。当child存在视图嵌套的时候 ConstraintLayout 可以减少测量和遍历次数,性能更好一点