Android onMeasure()测量流程解析

文章目录

    • Android onMeasure()测量流程解析
  • 前言
  • 布局与绘制流程文章
  • 组件测量的那些结论
  • 一、MeasureSpec:测量规则
  • 二、查看测量流程源码
    • 2.1 查看ViewRootImpl的PerformTraveals()方法
    • 2.2 View类的默认onMeasure()方法
    • 2.3 从FrameLayout的onMeasure()方法了解自定义ViewGroup的测量行为

前言

众所周知,Android 中组件显示到屏幕上需要经历测量、布局、绘制三个阶段,我们今天来了解一下测量的流程。


布局与绘制流程文章

Android onLayout()布局流程解析
Android onDraw()绘制流程解析

组件测量的那些结论

先看结论再看分析

1. )测量流程的起点是ViewRootImpl的PerformTraveals()方法 ,该方法调用performMeasure()方法,performMeasure()方法会调用根View(DecorView)的measure()方法,开启测量流程。也就是说测量流程是从根View开始的,准确来说是从根View的measure()方法开始的。因为根View是ViewGroup(FrameLayout),所以测量流程是从ViewGroup开始的。

2. )View 类有默认的onMeasure()实现,如果我们想实现自己的测量,需要重写onMeasure()方法。
根View(DecorView)是ViewGroup(FrameLayout), ViewGroup类继承自View类,View类的measure(int widthMeasureSpec, int heightMeasureSpec) 方法会调用onMeasure(widthMeasureSpec, heightMeasureSpec)方法,根据自身规则测量自己的宽高。而ViewGroup类并没有重写其父类View的onMeasure方法,Android提供给我们的系统组件(比如FrameLayout、LinearLayout等等)和我们自定义继承自View或ViewGroup的组件,一般都需要重写onMeasure()方法,如果不重写onMeasure()方法,组件是默认填满父布局的。

3. ) 对于根View(DecorView),其MeasureSpec由窗口的尺寸和其自身的LayoutParams共同决定的,对于普通View,其MeasureSpec由父容器的MeasureSpec和自身的LayoutParams共同决定的。

4. ) 自定义的ViewGroup测量一般会循环自身所有的子View,调用相应的方法(measureChildWithMargins()、measureChildren方法,这两个方法都会调用getChildMeasureSpec()方法)根据自己的MeasureSpec和子View的ViewGroup.LayoutParams生成子View的MeasureSpec,并传给子View的measure(int widthMeasureSpec, int heightMeasureSpec) 方法让子View进行自身的测量。等所有的子View完成测量后,ViewGroup会根据自己的布局规则(测量规则)和子View的测量宽高完成自身的测量。

一、MeasureSpec:测量规则

想要了解测量流程我们需要先了解MeasureSpec类,MeasureSpec是View类的一个内部类。MeasureSpec的作用在于:在Measure流程中,系统会将View的LayoutParams根据父容器所施加的规则转换成对应的MeasureSpec,然后在onMeasure方法中根据这个MeasureSpec来确定View的测量宽高,view可以有自己的宽高要求,但我们要考虑MeasureSpec的规则。

我们查看MeasureSpec的源码:

public static class MeasureSpec {private static final int MODE_SHIFT = 30;private static final int MODE_MASK  = 0x3 << MODE_SHIFT;/** @hide */@IntDef({UNSPECIFIED, EXACTLY, AT_MOST})@Retention(RetentionPolicy.SOURCE)public @interface MeasureSpecMode {}public static final int UNSPECIFIED = 0 << MODE_SHIFT;public static final int EXACTLY     = 1 << MODE_SHIFT;public static final int AT_MOST     = 2 << MODE_SHIFT;public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,@MeasureSpecMode int mode) {if (sUseBrokenMakeMeasureSpec) {return size + mode;} else {return (size & ~MODE_MASK) | (mode & MODE_MASK);}}@UnsupportedAppUsagepublic static int makeSafeMeasureSpec(int size, int mode) {if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {return 0;}return makeMeasureSpec(size, mode);}@MeasureSpecModepublic static int getMode(int measureSpec) {//noinspection ResourceTypereturn (measureSpec & MODE_MASK);}public static int getSize(int measureSpec) {return (measureSpec & ~MODE_MASK);}static int adjust(int measureSpec, int delta) {final int mode = getMode(measureSpec);int size = getSize(measureSpec);if (mode == UNSPECIFIED) {return makeMeasureSpec(size, UNSPECIFIED);}size += delta;if (size < 0) {Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +") spec: " + toString(measureSpec) + " delta: " + delta);size = 0;}return makeMeasureSpec(size, mode);}}

MeasureSpec是一个32位的int值,前2位是SpecMode,表示测量模式,后30位是SpecSize,表示在某种测量模式下的规格大小。MeasureSpec将SpecMode和SpecSize打包成一个int值来避免过多的对象内存分配,为了方便操作,其提供了打包的方法makeMeasureSpec,SpecMode和SpecSize也是一个int值,MeasureSpec也可以通过方法getMode和getSize得到原始的SpecMode和SpecSize。

SpecMode有三种值,如下所示。

  1. ) UNSPECIFIED
    父容器不对View有任何限制,要多大给多大,这种情况一般用于系统内部, 我们在开发过程中基本用不到。
  2. )EXACTLY
    父容器已经检测出View所需要的精确大小,这个时候View的最终大小就是SpecSize所指定的值。它对应于LayoutParams中的match_parent和具体的数值这两种模式。
  3. )AT_MOST
    父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值,具体是什么值要看不同View的具体实现。它对应于LayoutParams中的wrap_content。

二、查看测量流程源码

2.1 查看ViewRootImpl的PerformTraveals()方法

DecorView是视图的顶级View,我们添加的布局文件是它的一个子布局,而ViewRootImpl则负责渲染视图,它调用了一个performTraveals方法使得ViewTree开始三大工作流程,然后使得View展现在我们面前。该方法会依次调用:
performMeasure、performLayout、performDraw 进行测量布局绘制三大流程。
我们摘取其中一部分performMeasure代码查看:


WindowManager.LayoutParams lp = mWindowAttributes;
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {if (mView == null) {return;}Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");try {mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);} finally {Trace.traceEnd(Trace.TRACE_TAG_VIEW);}
}

根布局的MeasureSpec是怎么来的呢?是的,就是上面的getRootMeasureSpec,查看该方法。

private static int getRootMeasureSpec(int windowSize, int rootDimension) {int measureSpec;switch (rootDimension) {case ViewGroup.LayoutParams.MATCH_PARENT:measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);break;case ViewGroup.LayoutParams.WRAP_CONTENT:measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);break;default:measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);break;}return measureSpec;
}

参数windowSize窗口大小,rootDimension就是根布局ViewGroup.LayoutParams,我们会使用这两个参数通过MeasureSpec.makeMeasureSpec构建一个根布局的MeasureSpec。

然后我们看到在performMeasure方法中,调用了根布局的measure(int widthMeasureSpec, int heightMeasureSpec) 方法。根布局是ViewGroup ,而ViewGroup是没有measure方法的,只有ViewGroup的父类View有measure()方法。View的measure()方法中会调用onMeasure(widthMeasureSpec, heightMeasureSpec);方法进行测量。
我们继续查看View类的默认onMeasure()方法

2.2 View类的默认onMeasure()方法

View类的默认onMeasure()方法会进行默认的测量,测量结果是通过getDefaultSize()方法获取的。

setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));public static int getDefaultSize(int size, int measureSpec) {int result = size;int specMode = MeasureSpec.getMode(measureSpec);int specSize = MeasureSpec.getSize(measureSpec);switch (specMode) {case MeasureSpec.UNSPECIFIED:result = size;break;case MeasureSpec.AT_MOST:case MeasureSpec.EXACTLY:result = specSize;break;}return result;
}

可以看到,即使测量模式是AT_MOST,也返回了测量大小,这就是为什么我们自定义View时如果没有重写onMeasure()方法,设置自定义View是wrap_content,我们的组件会充满父布局的原因。
最后通过setMeasuredDimension方法存储我们测量的组件宽高。

根View 是FrameLayout,我们查看FrameLayout重写的onMeasure()方法。

2.3 从FrameLayout的onMeasure()方法了解自定义ViewGroup的测量行为

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {int count = getChildCount();final boolean measureMatchParentChildren =MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;mMatchParentChildren.clear();int maxHeight = 0;int maxWidth = 0;int childState = 0;for (int i = 0; i < count; i++) {final View child = getChildAt(i);if (mMeasureAllChildren || child.getVisibility() != GONE) {measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);final LayoutParams lp = (LayoutParams) child.getLayoutParams();maxWidth = Math.max(maxWidth,child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);maxHeight = Math.max(maxHeight,child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);childState = combineMeasuredStates(childState, child.getMeasuredState());if (measureMatchParentChildren) {if (lp.width == LayoutParams.MATCH_PARENT ||lp.height == LayoutParams.MATCH_PARENT) {mMatchParentChildren.add(child);}}}}// Account for padding toomaxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();// Check against our minimum height and widthmaxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());// Check against our foreground's minimum height and widthfinal Drawable drawable = getForeground();if (drawable != null) {maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());}setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),resolveSizeAndState(maxHeight, heightMeasureSpec,childState << MEASURED_HEIGHT_STATE_SHIFT));count = mMatchParentChildren.size();if (count > 1) {for (int i = 0; i < count; i++) {final View child = mMatchParentChildren.get(i);final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();final int childWidthMeasureSpec;if (lp.width == LayoutParams.MATCH_PARENT) {final int width = Math.max(0, getMeasuredWidth()- getPaddingLeftWithForeground() - getPaddingRightWithForeground()- lp.leftMargin - lp.rightMargin);childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);} else {childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,getPaddingLeftWithForeground() + getPaddingRightWithForeground() +lp.leftMargin + lp.rightMargin,lp.width);}final int childHeightMeasureSpec;if (lp.height == LayoutParams.MATCH_PARENT) {final int height = Math.max(0, getMeasuredHeight()- getPaddingTopWithForeground() - getPaddingBottomWithForeground()- lp.topMargin - lp.bottomMargin);childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);} else {childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,getPaddingTopWithForeground() + getPaddingBottomWithForeground() +lp.topMargin + lp.bottomMargin,lp.height);}child.measure(childWidthMeasureSpec, childHeightMeasureSpec);}}
}

可以看到该方法先循环子View,调用ViewGroup类的measureChildWithMargins()方法,对子View进行自身测量,在所有测量的子View中找到最大宽高,然后调用resolveSizeAndState处理后用setMeasuredDimension设置为自身的宽高,最后对MATCH_PARENT布局参数的子View进行重新测量。
这里我们不详细展开,有兴趣的可以自行查看,包括其他系统的布局组件,像LinearLayout、RelativeLayout等等,测量过程都会测量子View,然后按照自身的布局特点(布局规则)进行自身的测量。

我们主要看measureChildWithMargins()方法,相同作用的还有measureChild()方法,作用都是传入ViewGroup的测量规则和子View,调用getChildMeasureSpec 生成子View的测量规则。最后将生成的子View的测量规则传入child.measure()方法方法,让子View进行自身的测量。区别在于measureChildWithMargins会考虑Margins的影响,而measureChild方法不会。

protected void measureChildWithMargins(View child,int parentWidthMeasureSpec, int widthUsed,int parentHeightMeasureSpec, int heightUsed) {final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin+ widthUsed, lp.width);final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin+ heightUsed, lp.height);child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
protected void measureChild(View child, int parentWidthMeasureSpec,int parentHeightMeasureSpec) {final LayoutParams lp = child.getLayoutParams();final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,mPaddingLeft + mPaddingRight, lp.width);final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom, lp.height);child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

查看ViewGroup类的getChildMeasureSpec方法:通过父ViewGroup的测量规则和子View的布局参数,生成子View的测量规则,最后传递到子View的onMeasure()方法供自View进行自身大小的测量。
该方法展示的也就是网上流传最多的一张图片

public static int getChildMeasureSpec(int spec, int padding, int childDimension) {int specMode = MeasureSpec.getMode(spec);int specSize = MeasureSpec.getSize(spec);int size = Math.max(0, specSize - padding);int resultSize = 0;int resultMode = 0;switch (specMode) {case MeasureSpec.EXACTLY:if (childDimension >= 0) {resultSize = childDimension;resultMode = MeasureSpec.EXACTLY;} else if (childDimension == LayoutParams.MATCH_PARENT) {resultSize = size;resultMode = MeasureSpec.EXACTLY;} else if (childDimension == LayoutParams.WRAP_CONTENT) {resultSize = size;resultMode = MeasureSpec.AT_MOST;}break;case MeasureSpec.AT_MOST:if (childDimension >= 0) {resultSize = childDimension;resultMode = MeasureSpec.EXACTLY;} else if (childDimension == LayoutParams.MATCH_PARENT) {resultSize = size;resultMode = MeasureSpec.AT_MOST;} else if (childDimension == LayoutParams.WRAP_CONTENT) {resultSize = size;resultMode = MeasureSpec.AT_MOST;}break;case MeasureSpec.UNSPECIFIED:if (childDimension >= 0) {resultSize = childDimension;resultMode = MeasureSpec.EXACTLY;} else if (childDimension == LayoutParams.MATCH_PARENT) {resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;resultMode = MeasureSpec.UNSPECIFIED;} else if (childDimension == LayoutParams.WRAP_CONTENT) {resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;resultMode = MeasureSpec.UNSPECIFIED;}break;}return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

经过上面的查看,我们验证了开头的结论,Android组件整个测量的基本流程还是非常清晰的。

Android onMeasure()测量流程解析相关推荐

  1. Android View 测量流程(Measure)完全解析

    前言 上一篇文章,笔者主要讲述了DecorView以及ViewRootImpl相关的作用,这里回顾一下上一章所说的内容:DecorView是视图的顶级View,我们添加的布局文件是它的一个子布局,而V ...

  2. android开关机日志_(android 关机/重启)Android关机/重启流程解析

    --------------------------------Introduction-------------------------- 1. 在PowerManager的API文档中,给出了一个 ...

  3. BAT Android工程师面试流程解析+还原最真实最完整的一线公司面试题

    尊重原创,转载请写明原文出处:http://blog.csdn.net/sk719887916/article/details/47040931 (skay) 求职和我们每个人息息相关,而求职也有门道 ...

  4. android的布局流程,Android View 布局流程(Layout)全面解析

    前言 上一篇文章,笔者详细讲述了View三大工作流程的第一个,Measure流程,如果对测量流程还不熟悉的读者可以参考一下上一篇文章.测量流程主要是对View树进行测量,获取每一个View的测量宽高, ...

  5. android activity启动流程_1307页!一线大厂Android面试全套真题解析!

    /   前言   / 金九银十到了,很多读者都反映有面试的需求,所以我特地给大家准备了一点资料! 下面的题目都是大家在面试一线互联网大厂时经常遇到的面试真题和答案解析,如果大家还有其他好的题目或者好的 ...

  6. Android之View的绘制流程解析

    转载请标明出处:[顾林海的博客] 个人开发的微信小程序,目前功能是书籍推荐,后续会完善一些新功能,希望大家多多支持! ##前言 自定义View在Android中占据着非常重要的地位,因此了解View的 ...

  7. Android视图绘制流程完全解析,带你一步步深入了解View(二)

    在上一篇文章中,我带着大家一起剖析了一下LayoutInflater的工作原理,可以算是对View进行深入了解的第一步吧.那么本篇文章中,我们将继续对View进行深入探究,看一看它的绘制流程到底是什么 ...

  8. Android视图绘制流程完全解析(二)

    转载:http://blog.csdn.net/guolin_blog/article/details/16330267 https://segmentfault.com/a/119000000462 ...

  9. Android自定义控件入门到精通--View树的测量流程

    <Android自定义控件入门到精通>文章索引 ☞ https://blog.csdn.net/Jhone_csdn/article/details/118146683 <Andro ...

最新文章

  1. Python的闭包和装饰器
  2. Sabayon:治理 GNOME 用户的设置
  3. matlab支持的文件类型,MATLAB可以读取的数据文件类型有()
  4. 使用jQuery for Asp.Net 我的开发环境配置
  5. 安装server 2012 时提示输入的密码不满足网络或组管理员设置的密码复杂度
  6. 散谈游戏保护那点事~就从_TP开始入手吧
  7. React开发(240):dva概念5reducer
  8. C++|Qt工作笔记-对explicit的认识(Qt中一般情况下为什么会自动加上这个关键字)
  9. 拳王虚拟项目公社:闲鱼知乎引流售卖虚拟资源的虚拟副业项目实操
  10. 线程池拒绝策略-RejectedExecutionHandler
  11. ribbon基于接口配置超时_Spring Cloud第二篇:服务消费者RestTemplate+Ribbon
  12. 从开发到生产上线,如何确定集群大小?
  13. TI AM3352/54/59 工业核心板硬件说明书
  14. ARC093 F - Dark Horse
  15. 2010年度《影评达人》活动火…
  16. css-对号/叉号(纯css)
  17. x41t下使用工行华虹u盾
  18. solr 从数据库导入数据,全量索引和增量索引
  19. 数字签名与数字信封流程
  20. 12.Isaac教程--未来工厂中的搬运车

热门文章

  1. easyUI-树形菜单(ComboTree) 无限层级树实现方式(1.0版本)
  2. linux管理的救星,优秀SSH软件推荐:FinalShell SSH工具,服务器管理,远程桌面加速软件,支持Windows,Mac OS X,Linux
  3. 什么是异常?为什么要抛出异常?
  4. 用计算机名访问计算机,解决局域网用\\计算机名不能访问,用\\ip地址可访问
  5. React Diff算法详解
  6. 公众号可以优化排名吗
  7. UnicodeDecodeError: ‘utf-8‘ codec can‘t decode byte 0xfc in position 8: invalid start byte
  8. 了解EventLoop就明白为何 js 是单线程?| 前端面试基础
  9. 什么是备忘录?备忘录怎么扫描转文字?
  10. cadence使用技巧(三)— 自定义virtuoso ciw菜单