View的Measure

Android开发艺术探索笔记

SpecMode
  1. UNSPECIFIED,表示一种测量状态,对View的大小不做限制,要多大给多大。一般用于系统内部。
  2. EXACTLY,父容器已经知道View的精确大小,即SpecSize。对应于LayoutParams的match_parent。
  3. AT_MOST,父容器指定了一个最大的SpecSize,View不能大于该值,View具体的大小要看View的具体实现。对应于LayoutParams的wrap_content。
整体Measure流程

主要是分为MeasureSpec和Measure两个过程

  1. MeasureSpec过程是根据View自身的LayoutParams和其父控件的MeasureSpec来确定View的MeasureSpec。顶级父控件DecorView的MeasureSpec由窗口的尺寸和自身的LayoutParams决定。
  2. Measure过程是根据View的MeasureSpec来测量的宽/高度(View的最终宽高和四个顶点的位置在layout结束后确定)。
MeasureSpec的过程

分为顶层View即DecorView,和普通View(包含ViewGroup)两种情况:
. DecorView,其MeasureSpec由窗口的尺寸和自身的LayoutParams决定。
. 普通View,其MeasureSpec由父容器的MeasureSpec和自身的LayoutParams共同决定。

  1. DecorView的MeasureSpec的创建过程
    DecorView对应的实现类是ViewRootImpl。MeasureSpec从measureHierarchy方法开始。
    先码上measureHierarchy的所有代码,看看就好:
if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
            // On large screens, we don't want to allow dialogs to just
            // stretch to fill the entire width of the screen to display
            // one line of text.  First try doing the layout at a smaller
            // size to see if it will fit.
            final DisplayMetrics packageMetrics = res.getDisplayMetrics();
            res.getValue(com.android.internal.R.dimen.config_prefDialogWidth, mTmpValue, true);
            int baseSize = 0;
            if (mTmpValue.type == TypedValue.TYPE_DIMENSION) {
                baseSize = (int)mTmpValue.getDimension(packageMetrics);
            }
            if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": baseSize=" + baseSize);
            if (baseSize != 0 && desiredWindowWidth > baseSize) {
                childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
                if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
                        + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
                if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
                    goodMeasure = true;
                } else {
                    // Didn't fit in that size... try expanding a bit.
                    baseSize = (baseSize+desiredWindowWidth)/2;
                    if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": next baseSize="
                            + baseSize);
                    childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
                    if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
                            + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
                    if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
                        if (DEBUG_DIALOG) Log.v(TAG, "Good!");
                        goodMeasure = true;
                    }
                }
            }
        }

measureHierarchy()中的参数:desiredWindowWidth窗口的宽 ;desiredWindowHeight窗口的高
measureHierarchy会处理WRAP_CONTENT时的大屏的特殊情况,见如下的注释

if (lp.width == ViewGroup.LayoutParams.WRAP_CONTENT) {
            // On large screens, we don't want to allow dialogs to just
            // stretch to fill the entire width of the screen to display
            // one line of text.  First try doing the layout at a smaller
            // size to see if it will fit.

measureHierarchy中大部分代码都是用来处理这个逻辑的。剩下关于MeasureSpec的代码只有短短三行

 childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);

MeasureSpec的逻辑重点自然在getRootMeasureSpec()方法中。其注释就直白的说明了

 /**
     * Figures out the measure spec for the root view in a window based on it's
     * layout params.
     * 根据root view的 layout params确定其measure spec
     * @param windowSize
     *            The available width or height of the window
     *
     * @param rootDimension
     *            The layout params for one dimension (width or height) of the
     *            window.
     *
     * @return The measure spec to use to measure the root view.
     */
    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.EXACTLY的精确模式,大小为窗口大小。
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            //对应MeasureSpec.AT_MOST的最大模式,大小不能超过窗口大小。
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            //对应MeasureSpec.EXACTLY的精确模式,大小为布局中的指定大小
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }
  1. 普通View的MeasureSpec的创建过程
    View的measure的ViewGroup的measureChildWithMargins开始
   /**
     * Ask one of the children of this view to measure itself, taking into
     * account both the MeasureSpec requirements for this view and its padding
     * and margins. The child must have MarginLayoutParams The heavy lifting is
     * done in getChildMeasureSpec.
     *
     * @param child The child to measure
     * @param parentWidthMeasureSpec The width requirements for this view
     * @param widthUsed Extra space that has been used up by the parent
     *        horizontally (possibly by other children of the parent)
     * @param parentHeightMeasureSpec The height requirements for this view
     * @param heightUsed Extra space that has been used up by the parent
     *        vertically (possibly by other children of the parent)
     */
    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);
    }

又上面代码可以看出MeasureSpec的逻辑代码自然是在getChildMeasureSpec()中。也可以看出,在确定好MeasureSpec后,就开始了child的measure流程
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
下面看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);
       //首先说下padding参数,以宽度为例。由measureChildWithMargins方法看出,该参数是将ViewGroup的 
       //左右padding,view自身的左右margin以及ViewGroup中已经被占用的宽度。由此可以看出,
       //无论view怎样,其宽度都不能超过lp.width - padding

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY: //父控件为精确模式EXACTLY时
            if (childDimension >= 0) {            //1. 1View布局中为具体大小值
                resultSize = childDimension;  // view为EXACTLY,大小为布局中指定的值
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) { //1.2 View为MATCH_PARENT
                // Child wants to be our size. So be it.
                resultSize = size;             //View可以精确到和父控件一样大,所以View为EXACTLY模式
                resultMode = MeasureSpec.EXACTLY;  //大小为父控件可用的大小(除掉了padding)
            } else if (childDimension == LayoutParams.WRAP_CONTENT) { //1.3 View为WRAP_CONTENT
                // Child wants to determine its own size. It can't be
                // bigger than us.  //此时View大小随内容变化,但不能超过父控件的可用空间
                resultSize = size; //所以View为AT_MOST最大模式
                resultMode = MeasureSpec.AT_MOST; //大小为父控件可用的大小(除掉了padding)
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:  //父控件为AT_MOST最大模式
            if (childDimension >= 0) {  //2.1 View布局中为具体大小值
                // Child wants a specific size... so be it
                resultSize = childDimension; // view为EXACTLY,大小为布局中指定的值
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {//2.2View为MATCH_PARENT
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size; //View大小和父控件一样,不能超过父控件的最大值
                resultMode = MeasureSpec.AT_MOST; //View为最大模式,大小不能超过父控件的可用空间
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {//2.3 View为WRAP_CONTENT
                // Child wants to determine its own size. It can't be
                // bigger than us. //View大小随内容变化,打不能超过超过父控件的可用空间
                resultSize = size;  //所以View为AT_MOST最大模式
                resultMode = MeasureSpec.AT_MOST;  //大小为父控件可用的大小(除掉了padding)
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED: //父控件为UNSPECIFIED未指定模式
            if (childDimension >= 0) { //3.1View布局中为具体大小值
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY; // view为EXACTLY,大小为布局中指定的值
            } else if (childDimension == LayoutParams.MATCH_PARENT) {//3.2View为MATCH_PARENT
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED; //View也为UNSPECIFIED,大小为0
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {//3.3View为WRAP_CONTENT
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;//View也为UNSPECIFIED,大小为0
            }
            break;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }
measure流程

分为View的measure过程和ViewGroup的measure过程。

  1. View的measure过程
    ViewGroup在measureChildWithMargins中确定了View的MeasureSpec后调用
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);

View的measure方法是个final方法,但其中会调用onMeasure();

 public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
...
if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } 
...
}

View的onMeasure方法如下:

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

setMeasuredDimension()方法会设置View的宽高,如果我们在重写onMeasure时,也一定要该方法,是宽高生效。
默认的宽高逻辑代码在getDefaultSize()中

 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;
    }

逻辑很简单MeasureSpec.AT_MOST和 MeasureSpec.EXACTLY模式时,View的大小即specSize。
MeasureSpec.UNSPECIFIED时View的大小为第一个参数(以宽为例),即onMeasure传过来的getSuggestedMinimumWidth。

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

这里的逻辑是,如果View没有设置背景,则去mMinWidth,对应的是android:minWidth设置的值;如果View设置了背景,怎取背景的getMinimumWidth()值和minWidth中大的那个.
背景的getMinimumWidth()也很简单,即有原始宽高时取原始宽高,没有取0.

public int getMinimumWidth() {
        final int intrinsicWidth = getIntrinsicWidth();
        return intrinsicWidth > 0 ? intrinsicWidth : 0;
    }

总结,View的测量问题在于:View在WRAP_CONTENT时,其最终的模式时AT_MOST,且大小是父控件的可用大小。这和MATCH_PARENT时没有区别。因此在自定义View时,我们要处理View在WRAP_CONTENT时的这一问题。

  1. ViewGroup的measure过程
    ViewGroup比较简单,它的measure流程和View一样,作为其父控件的子View处理,不同的是,ViewGroup没有重写onMeasure方法,而是交给其子类去按需实现。
    以LinearLayout为例。LinearLayout会遍历子View,一次调用子View的measure方法,并纪录每个子View的测量值,最后再测量自己的大小。
获取View的宽高

因为Activity的生命周期和View的测量是异步的,所以并不能在Activity的生命周期函数中直接获取。通常可以通过以下几种方式获取:

  1. onWindowsFocusChanged
    这个回调函数在View初始化完成后调用,所以在这里获取宽高可以确保是View测量后的宽高。需要注意的是,该函数在Activity失去和获取焦点的时候都会触发。
public void onWindowsFocusChanged(boolean hasFocus){
     super.onWindowsFocusChanged(hasFocus);
     if (hasFocus) {
          int width = view.getMeasureWidth();
          int herght = view.getMeasureHeight();
     }
}
  1. view.post(runnable)
    此方法通过post将一个runnable投递到消息队列的尾部,因为在尾部,所以此runnable被Looper处理时,View已经测量完成了。
protected void omStart(){
    super.omStart();
    view.post(new Runnable(){
        @override
        public void run(){
            int width = view.getMeasureWidth();
            int herght = view.getMeasureHeight();
        }
    });
}
  1. ViewTreeObserverd的OnGlobalLayoutListener接口
    OnGlobalLayoutListener中的onGlobalLayout方法会在View树的状态发生变化时回调。注意,此方法回多次调用
protected void onStart(){
    super.onStart();
    ViewTreeOberver observer = view.getViewTreeObserver();
    observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
        @Override
         public void onGlobalLayout() {
         view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
         int width = view.getMeasureWidth();
         int herght = view.getMeasureHeight();
         }
    }
   )
}

4.view.measure(int widthMeasureSpec , int heightMeasureSpec)
手动触发测量

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

推荐阅读更多精彩内容