进入Activity时,为何页面布局内View#onMeasure会被调用两次?

简介: 进入Activity时,为何页面布局内View#onMeasure会被调用两次?

确切的说,是刚打开Activity时,页面中的View的onMeasure最少会被调用两次。这是为什么呢?接下来我们以LinearLayout为例进行分析。

系列文章:

从源码角度理解FrameLayout#onMeasure对child的measure调用次数

从源码角度理解LinearLayout#onMeasure对child的measure调用次数

从源码角度理解RelativeLayout#onMeasure对child的measure调用次数

从源码角度理解ConstraintLayout#onMeasure对child的measure调用次数

ViewGroup在调用onMeasure时,会先测量父View,还是会先测量子View?

自定义LinearLayout验证

先自定义一个LinearLayout:CustomLinearLayout,主要是添加了log打印:

CustomLinearLayout打印log

public class CustomLinearLayout extends LinearLayout {
    private static final String TAG = "CustomLayout-Linear";

    public CustomLinearLayout(Context context) {
        super(context);
    }

    public CustomLinearLayout(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomLinearLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public CustomLinearLayout(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        Log.e(TAG, String.format("onMeasure widthSpecSize:%s, widthSpecMode:%s, heightSpecSize:%s, heightSpecMode:%s",
                widthSpecSize, widthSpecMode, heightSpecSize, heightSpecMode));
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        Log.e(TAG, String.format("onLayout changed:%s, l:%s, t:%s, r:%s, b:%s",
                changed, l, t, r, b));
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.e(TAG, "onDraw");
    }
}

简单的xml文件,宽高都是match_parent

接着看下Activity对应的布局文件,布局文件很简单,就一个自定义LinearLayout:

<?xml version="1.0" encoding="utf-8"?>
<com.tinytongtong.androidstudy.measure.view.CustomLinearLayout 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=".measure.MeasureInvokeTestActivity">

</com.tinytongtong.androidstudy.measure.view.CustomLinearLayout>

查看log

最后启动Activity,我们看下对应的log:

E/CustomLayout-Linear: onMeasure widthSpecSize:1080, widthSpecMode:1073741824, heightSpecSize:1823, heightSpecMode:1073741824
E/CustomLayout-Linear: onMeasure widthSpecSize:1080, widthSpecMode:1073741824, heightSpecSize:1823, heightSpecMode:1073741824
E/CustomLayout-Linear: onLayout changed:true, l:0, t:0, r:1080, b:1823

如上所示,自定义LinearLayout的onMeasure方法确实是调用了两次。

通过debug分析原理

我们在CustomLinearLayout#onMeasure方法中添加一个debug断点,看下实际的调用链。

debug结果:基于api30
第一次调用onMeasure:
在这里插入图片描述
从图中可以清晰的看出,ViewRootImpl#performMeasure方法是在ViewRootImpl的2228行调用。调用链如下:

--> ViewRootImpl#performTraversals
--> ViewRootImpl#measureHierarchy; 2486行调用
--> ViewRootImpl#performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 2228行调用
--> View#measure; 开始执行页面绘制流程
--> View#onMeasure; 从根View开始,从上往下,依次执行依次measure流程。

具体源码如下:ViewRootImpl#performTraversals方法中,2486行。

private void performTraversals() {
    ...
    // Ask host how big it wants to be
    windowSizeMayChange |= measureHierarchy(host, lp, res,
            desiredWindowWidth, desiredWindowHeight);
    ...
}

4、第二次调用onMeasure:
在这里插入图片描述

调用链如下:

--> ViewRootImpl#performTraversals
--> ViewRootImpl#performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); 2280行调用
--> View#measure; 开始执行页面绘制流程
--> View#onMeasure; 从根View开始,从上往下,依次执行依次measure流程。

具体代码如下:

private void performTraversals() {
    ...
    // Ask host how big it wants to be
    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
    ...
}

总体来说,两次测量都是ViewRootImpl#performTraversals方法中触发的,第一次是在2486行调用ViewRootImpl#measureHierarchy方法,第二次是在2280行调用ViewRootImpl#performMeasure(childWidthMeasureSpec, childHeightMeasureSpec)。

这两次调用各自是什么意思呢?
第一次是在2486行调用ViewRootImpl#measureHierarchy方法,这一步骤的测量ViewTree是为了确定RootView的尺寸从而在此步骤确定Window尺寸。

第二次是在2280行调用ViewRootImpl#performMeasure(childWidthMeasureSpec, childHeightMeasureSpec)方法,是在确定了window尺寸的基础上,对RootView进行再次测量,本次就可确定ViewTree中各部分的尺寸。

细心的同学可能已经发现了,我们demo中Activity布局的宽高,写的都是match_parent,属于测量中最简单的场景,此时RootView的宽高是不会超出window尺寸的。如果我们修改一下我们布局的宽高,那么测量流程就不止两次了。感兴趣的同学可以研究下,具体参见Android 一个困惑很久的问题:onMeasure() 为什么会执行多次?。

总结

在一个简单的Activity中,写一个简单的布局,宽高都是match_parent。当打开Activity时,从RootView开始从上往下,绘制流程(onMeasure方法)最少执行两次。

相关资料

Android 一个困惑很久的问题:onMeasure() 为什么会执行多次?

demo地址

系列文章:

从源码角度理解FrameLayout#onMeasure对child的measure调用次数

从源码角度理解LinearLayout#onMeasure对child的measure调用次数

从源码角度理解RelativeLayout#onMeasure对child的measure调用次数

从源码角度理解ConstraintLayout#onMeasure对child的measure调用次数

ViewGroup在调用onMeasure时,会先测量父View,还是会先测量子View?

相关文章
|
Java Android开发
EventBus简单介绍
EventBus简单介绍
517 0
|
存储 Java API
Android 浅度解析:mk预置AAR、SO文件、APP包和签名
Android 浅度解析:mk预置AAR、SO文件、APP包和签名
3065 0
|
前端开发 C++ iOS开发
几款主流好用的markdown编辑器介绍
几款主流好用的markdown编辑器介绍
2104 1
|
监控 网络协议 Java
IO 多路复用? 什么是 IO 多路复用? 简单示例(日常生活)来解释 IO 多路复用 一看就懂! 大白话,可爱式(傻瓜式)教学! 保你懂!
本文通过日常生活中的简单示例解释了IO多路复用的概念,即一个线程通过监控多个socket来处理多个客户端请求,提高了效率,同时介绍了Linux系统中的select、poll和epoll三种IO多路复用的API。
1157 3
|
Android开发
Android studio 2021.3.1不生成iml文件
Android studio 2021.3.1不生成iml文件
836 5
|
Java 开发工具 Android开发
Android Studio利用Build.gradle导入Git commit ID、Git Branch、User等版本信息
本文介绍了在Android Studio项目中通过修改`build.gradle`脚本来自动获取并添加Git的commit ID、branch名称和用户信息到BuildConfig类中,从而实现在编译时将这些版本信息加入到APK中的方法。
844 0
|
Rust 网络协议 安全
揭开Rust网络编程的神秘面纱:全新的Socket体验,让你告别内存泄漏的噩梦!
【8月更文挑战第31天】Rust语言凭借其卓越的内存安全性和高性能,在网络编程领域展现出独特优势。本文将带你探索Rust中的Socket编程,展示如何使用标准库`std::net`模块轻松实现TCP服务器与客户端。通过简洁的代码示例,你将看到Rust如何简化网络通信流程,并通过`async/await`异步模型高效处理并发连接。此外,Rust社区提供的优秀库如`tokio`和`async-std`进一步增强了异步网络编程的能力。无论是从基础示例还是高级应用,Rust都将为你带来耳目一新的网络编程体验。
1717 0
|
存储 芯片
Rockchip 自定义vendorstorages数据再u-boot通过cmdline给kernel传递数据
Rockchip 自定义vendorstorages数据再u-boot通过cmdline给kernel传递数据
1675 1
|
关系型数据库 MySQL 数据库连接
Go语言中使用sqlx来操作事务
在应用中,数据库事务保证操作的ACID特性至关重要。`github.com/jmoiron/sqlx`简化了数据库操作。首先安装SQLX和MySQL驱动:`go get github.com/jmoiron/sqlx`和`go get github.com/go-sql-driver/mysql`。导入所需的包后,创建数据库连接并使用`Beginx()`方法开始事务。通过`tx.Commit()`提交或`tx.Rollback()`回滚事务以确保数据一致性和完整性。
430 0
|
Android开发
Android Activity跳转详解
Android Activity跳转详解
1713 0