Android自定义View

LinearLayout的onMeasure测量流程

2019-02-13  本文已影响24人  世道无情

1. 概述


下边通过示例代码分析, LinearLayout 的 onMeasure 流程:
场景:LinearLayout中有 3个 TextView,方向为垂直方向

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.jackchen_view.MainActivity">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="王子文"
            android:id="@+id/text_view"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="王子文" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="王子文" />
    </LinearLayout>

</LinearLayout>

LinearLayout的 垂直方向,测量流程如下:
从最外层的 ViewRootImpl 向最里层的 TextView 递归:
1>:把 ViewRootImpl 的测量模式 传递给 DecorView,然后 DecorView 把测量模式 传递给 LinearLayout,然后 LinearLayout通过for循环把 测量模式给 TextView,最后 TextView把 测量模式给 setMeasuredDimension,这个方法 此时就会指定 TextView 的宽高;
2>:等 测量好宽高后,就表示 所有子View的宽高已经测量完毕,此时 LinearLayout 会拿 所有子View的高度,就是 3个TextView的高度,来测量自己的高度;

如下图所示:


图片.png

2. LinearLayout和RelativeLayout高度的计算


1>:LinearLayout:如果是垂直方向,就叠加所有子view高度;
2>:RelativeLayout:如果高度是 wrap_content,那么高度取 子孩子中 高度最高的;

上一篇 下一篇

猜你喜欢

热点阅读