View的工作流程——measure

写在前面

今天和老爸去医院了,老爸最近腰疼,幸好没什么事,各位也要多多爱惜自己的身体,等身体出了问题就来不及了。好了,闲话到此为止,话说《开发艺术探索》里面不少东西我早就看了,但是因为自己当时水平有限,而且有很多也看不大懂,所以看了忘是挺正常的事。不过感觉随着工作经验的增长,以前大学里上过《操作系统》、《计算机网络》、《数据结构》等一些课都被串到了一起,感觉很好,而且愈发能感觉到自己的不足了。这周的文主要算是一篇读书笔记吧,记一下读《开发艺术探索》第四章和View相关的笔记,至于ViewGroup我觉得还需要过段时间,在沉淀一下再来和各位一起探索一下。而且说真的,这篇文我也是硬着头皮写下来的,因为看源码看着看着发现我疑问越来越多,很多都是现阶段暂时无法解决的,不过问题总是一个一个去解决的,先过一遍View的measure流程再说其他的。

ViewRoot & DecorView

ViewRoot对应于ViewRootImpl类,在ViewRootImpl类中有如下一段注释:

/** 
 * The top of a view hierarchy, implementing the needed 
 * protocol between View and the WindowManager.
 */ 

View层最顶部,实现了View和WindowManager间所需的协议。这个类很重要,但是我现在对其理解也不是很深(一是因为读源码无力,一是没有系统的阅读过源码),所以就拿书上的话来说:它是连接WindowManager和DecorView的纽带,View的三大流程均是通过ViewRoot来完成的。在ActivityThread中(同样很有意思的一点是ActivityThread是一个类,并非线程什么的,当然了如果哪一天我读通了这一块回来和各位分享的),当Activity对象被创建完毕后,会将DecorView添加到Window中,同时会创建ViewRootImpl对象,并将ViewRootImpl对象和DecorView建立关联。

接下来直接放结论,尽快进入正题:
View的绘制流程是从ViewRoot的performTraversals开始的,它经过measure、layout和draw三个过程才能最终将一个View绘制出来。

MeasureSpec

在之前Android自定义View你需要知道的一些东西中我已经简要的介绍过MeasureSpec了,当然在这不敢再麻烦各位去看了,继续简介一下,熟悉的可以跳过这段。

首先咱直接看他的注释,看看注释是怎么解释这玩意的:

/**
     * A MeasureSpec encapsulates the layout requirements passed from parent to child.
     * Each MeasureSpec represents a requirement for either the width or the height.
     * A MeasureSpec is comprised of a size and a mode. There are three possible
     * modes:
     * <dl>
     * <dt>UNSPECIFIED</dt>
     * <dd>
     * The parent has not imposed any constraint on the child. It can be whatever size
     * it wants.
     * </dd>
     *
     * <dt>EXACTLY</dt>
     * <dd>
     * The parent has determined an exact size for the child. The child is going to be
     * given those bounds regardless of how big it wants to be.
     * </dd>
     *
     * <dt>AT_MOST</dt>
     * <dd>
     * The child can be as large as it wants up to the specified size.
     * </dd>
     * </dl>
     *
     * MeasureSpecs are implemented as ints to reduce object allocation. This class
     * is provided to pack and unpack the <size, mode> tuple into the int.
     */

最上面那段话的大概意思是一个MeasureSpec封装了一个从父(控件)传给子(控件)的布局要求。每个MeasureSpec代表的不是宽就是高的要求。一个MeasureSpec包含了一个尺寸和一个(测量)模式,这些模式如下:

  • UNSPECIFIED
    父(容器)对子(控件)没有任何限制,子控件可以想要多大就有多大。

  • EXACTLY
    父容器已经决定了子控件的精确尺寸,子控件将会变成被给出的约束大小,不管他自己想要变成啥样。

  • AT_MOST
    子控件可以和和他想要的规格尺寸一样大。

最后一段话解释了一下为什么这么实现,暂时不需要咱关心这些。看完了注释基本上已经对MeasureSpec有了一个基本的认识了。但是看完这段注释,应该会产生一个疑惑,在注释中说MeasureSpec是父传递给子的,那么最顶层的DecorView的MeasureSpec是如何来的呢?《开发艺术探索》上说是在ViewRootImpl的measureHierarchy方法中创建的,主要代码如下:

childWidthMeasureSpec = getRootMeasureSpec(desiredWindowWidth,lp.width);
childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight,lp.width);
performMeasure(childWidthMeasureSpec,childHeightmeasureSpec);

其中desiredWindowWidth和desiredWindowHeight就是屏幕的尺寸,追踪下getRootMeasureSpec()源码看看:

    private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

可以看到该方法中对于match_parent、wrap_content和其余情况的处理:

  • LayoutParams.MATCH_PARENT:采用精确模式测量,大小是窗口大小

  • LayoutParams.WRAP_CONTENT:大小不定,最大是窗口大小

  • 其他:结合我们平时写xml和代码的经验,此处其他应该就是我们制定了大小(比如100dp),大小为指定大小。

View的MeasureSpec的获取

上面的MeasureSpec注释里说了,是从父传递到子的,那么View很明显是一个子布局,让我们上ViewGroup里找找child是如何获取MeasureSpec的:

    /**
     * Ask all of the children of this view to measure themselves, taking into
     * account both the MeasureSpec requirements for this view and its padding.
     * We skip children that are in the GONE state The heavy lifting is done in
     * getChildMeasureSpec.
     *
     * @param widthMeasureSpec The width requirements for this view
     * @param heightMeasureSpec The height requirements for this view
     */
    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
        final int size = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < size; ++i) {
            final View child = children[i];
            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
    }

老规矩,先让我这个渣渣来翻译一下注释……
遍历View去测量他们自身,既要考虑MeasureSpec的要求又要考虑padding。跳过GONE状态的(不测量这个状态的View),更繁重的事在getChildMeasureSpec完成。

很明显,咱得看一下getChildMeasureSpec方法了:

    /**
     * Does the hard part of measureChildren: figuring out the MeasureSpec to
     * pass to a particular child. This method figures out the right MeasureSpec
     * for one dimension (height or width) of one child view.
     *
     * The goal is to combine information from our MeasureSpec with the
     * LayoutParams of the child to get the best possible results. For example,
     * if the this view knows its size (because its MeasureSpec has a mode of
     * EXACTLY), and the child has indicated in its LayoutParams that it wants
     * to be the same size as the parent, the parent should ask the child to
     * layout given an exact size.
     *
     * @param spec The requirements for this view
     * @param padding The padding of this view for the current dimension and
     *        margins, if applicable
     * @param childDimension How big the child wants to be in the current
     *        dimension
     * @return a MeasureSpec integer for the child
     */
    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) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

咱继续翻译一下……
困难的事咱来做:算出MeasureSpec传递给
一个child。这个方法为一个子view的一个尺寸(高或宽)算出正确的MeasureSpec。

他的目的是组合MeasureSpec和LayoutParams的信息让child获取最好的可能结果。例如:如果这个view知道他的尺寸(因为测量模式是EXACTLY),这个child已经指出了他的LayoutParams,他想和他的父容器有一样的尺寸(match_parent),这时父容器应该要求child布局成被给的精确尺寸。

从上面的注释我们可以了解到,子View的MeasureSpec并不是由其自身的LayoutParams决定的,而是由其父容器和其自身的LayoutParams一同决定的。接下来看一下代码,看看究竟是怎么操作的:

  • 首先从ViewGroup的宽/高的MeasureSpec中获取到对应的specMode,然后根据不同的mdoe去执行不同的操作

  • EXACTLY:如果子View指定了精确值的大小,那么测量模式是EXACTLY,尺寸是传入的childDimension,这两个值将会被打包成一个MeasureSpec并返回。如果childDimension等于MATCH_PARENT,那么就将上面获取到的自身尺寸和EXACTLY模式打包成一个MeasureSpec打包并返回。如果childDimension等于WRAP_CONTENT,那么将自身尺寸赋给孩子的尺寸,让子View的尺寸不要大于父容器就行了,将这个尺寸和AT_MOST模式打包并返回。

之后的AT_MOST和UNSPECIFIED测量模式和EXACTLY的套路差不多,就不一一看过去了,《Android开发艺术探索》上总结了一个表格:

|columns:childLayoutParams/rows:parentSpecMode|EXACTILY|AT_MOST|UNSPECIFIED
| ------------ |:-----------------: | ------: |
|dp/px|EXACTLY/childSize|EXACTLY/childSize|EXACTLY/childSize|
|match_parent|EXACTLY/parentSize|AT_MOST/parentSize|UNSPECIFIED/0|
|wrap_content|AT_MOST/parentSize|AT_MOST/parentSize|UNSPECIFIED/0|

最后要强调一句和《开发艺术探索》上一样的话,以上的表格并非是经验总结,而是将代码具现为一个表格罢了。

View的measure流程

终于填完了几个比较重要的坑,可以来讲讲View的measure流程了。View的测量是由measure()方法实现的 ,在measure()方法中会去调用onMeasure()方法,看一下View的onMeasure()方法的实现:

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }

关于这个方法有一些要注意的地方,在以前的Android自定义View你需要知道的一些东西都有说过,而且这个方法的注释里都有写你需要注意的东西,感兴趣的可以去看看,这里就不赘述了。以上方法调用了setMeasuredDimension方法设置View宽高,因此我们看一下他是如何获取宽高的就可以了,不多说,看源码:

    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和EXACTLY:那么就返回View测量后的大小,如果是UNSPECIFIED模式那么就返回传入的size值。接下来看看传入的这个size值是怎么获取的:

    protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }

从以上代码我们可以看出,如果view有背景则从最小宽度和background的宽度中返回较大的那个,如果没有背景则返回最小宽度,这个最小宽度我们可以通过xml或者setMinimumWidth来设置,默认为0。

接下来通过一个问题来回忆一下今天所了解的东西:在View中使用wrap_content为什么效果和match_parent效果一样?
首先这个问题需要去ViewGroup里看看,因为View的MeasureSpec是从ViewGroup中传递而来的,前面我们画的那张表格就是处理代码的具现,我们可以直接查表~

查表可知在match_parent和wrap_content这两种情况下传递给View的size都是parentSize(忽略UNSPECIFIED的情况),那么再看看View有没有对这两种情况做特殊的处理就行了。而在上面的getDefaultSize方法里可以看到AT_MOST和EXACTLY两种模式返回值都是相同的,因此在自定义继承于View的控件时需要我们去重写onMeasure()方法来处理wrap_content的情况。

读到这你可能会发现View和ViewGroup这俩货根本分不开,事实也是如此,但是在这我就不继续记我的笔记了,因为有些事我也没想明白,所以留待以后填坑吧(立了个flag)。

后记

还有一个ViewGroup的measure流程这里并没有继续了,想留着以后再来填这个坑吧。记得原来读《Android开发艺术探索》都是:“哦,原来是这样的” 状态,现在读则是会对一些代码的流程产生疑惑,而这些疑惑以我现在水平还是有些难以解决的。不过学习就是不断完善和不断有新的问题的过程,如同我们初中高中所学的物理一样,很多时候我们学到的只是相对正确的知识,但是在以后不断学习的过程中,我们可以不断的纠正自己以前的错误和带有局限的理解。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容