Android View 測量流程(Measure)完全解析

yangxi_001發表於2017-01-06

前言

上一篇文章,筆者主要講述了DecorView以及ViewRootImpl相關的作用,這裡回顧一下上一章所說的內容:DecorView是檢視的頂級View,我們新增的佈局檔案是它的一個子佈局,而ViewRootImpl則負責渲染檢視,它呼叫了一個performTraveals方法使得ViewTree開始三大工作流程,然後使得View展現在我們面前。本篇文章主要內容是:詳細講述View的測量(Measure)流程,主要以原始碼的形式呈現,原始碼均取自Android API 21.

從ViewRootImpl#PerformTraveals說起

我們直接從這個方法說起,因為它是整個工作流程的核心,我們看看它的原始碼:

private void performTraversals() {
            ...

        if (!mStopped) {
            int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);  // 1
            int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
            performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);       
            }
        } 

        if (didLayout) {
            performLayout(lp, desiredWindowWidth, desiredWindowHeight);
            ...
        }


        if (!cancelDraw && !newSurface) {
            if (!skipDraw || mReportNextDraw) {
                if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
                    for (int i = 0; i < mPendingTransitions.size(); ++i) {
                        mPendingTransitions.get(i).startChangingAnimations();
                    }
                    mPendingTransitions.clear();
                }

                performDraw();
            }
        } 
        ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

方法非常長,這裡做了精簡,我們看到它裡面主要執行了三個方法,分別是performMeasure、performLayout、performDraw這三個方法,在這三個方法內部又會分別呼叫measure、layout、draw這三個方法來進行不同的流程。我們先來看看performMeasure(childWidthMeasureSpec, childHeightMeasureSpec)這個方法,它傳入兩個引數,分別是childWidthMeasureSpec和childHeightMeasure,那麼這兩個引數代表什麼意思呢?要想了解這兩個引數的意思,我們就要先了解MeasureSpec

理解MeasureSpec

MeasureSpec是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.它的意思就是說,該類封裝了一個View的規格尺寸,包括View的寬和高的資訊,但是要注意,MeasureSpec並不是指View的測量寬高,這是不同的,是根據MeasueSpec而測出測量寬高。 
MeasureSpec的作用在於:在Measure流程中,系統會將View的LayoutParams根據父容器所施加的規則轉換成對應的MeasureSpec,然後在onMeasure方法中根據這個MeasureSpec來確定View的測量寬高。 
我們來看看這個類的原始碼:

public static class MeasureSpec {
        private static final int MODE_SHIFT = 30;
        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;

        /**
          * UNSPECIFIED 模式:
          * 父View不對子View有任何限制,子View需要多大就多大
          */ 
        public static final int UNSPECIFIED = 0 << MODE_SHIFT;

        /**
          * EXACTYLY 模式:
          * 父View已經測量出子Viwe所需要的精確大小,這時候View的最終大小
          * 就是SpecSize所指定的值。對應於match_parent和精確數值這兩種模式
          */ 
        public static final int EXACTLY     = 1 << MODE_SHIFT;

        /**
          * AT_MOST 模式:
          * 子View的最終大小是父View指定的SpecSize值,並且子View的大小不能大於這個值,
          * 即對應wrap_content這種模式
          */ 
        public static final int AT_MOST     = 2 << MODE_SHIFT;

        //將size和mode打包成一個32位的int型數值
        //高2位表示SpecMode,測量模式,低30位表示SpecSize,某種測量模式下的規格大小
        public static int makeMeasureSpec(int size, int mode) {
            if (sUseBrokenMakeMeasureSpec) {
                return size + mode;
            } else {
                return (size & ~MODE_MASK) | (mode & MODE_MASK);
            }
        }

        //將32位的MeasureSpec解包,返回SpecMode,測量模式
        public static int getMode(int measureSpec) {
            return (measureSpec & MODE_MASK);
        }

        //將32位的MeasureSpec解包,返回SpecSize,某種測量模式下的規格大小
        public static int getSize(int measureSpec) {
            return (measureSpec & ~MODE_MASK);
        }
        //...
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45

可以看出,該類的思路是相當清晰的,對於每一個View,包括DecorView,都持有一個MeasureSpec,而該MeasureSpec則儲存了該View的尺寸規格。在View的測量流程中,通過makeMeasureSpec來儲存寬高資訊,在其他流程通過getMode或getSize得到模式和寬高。那麼問題來了,上面提到MeasureSpec是LayoutParams和父容器的模式所共同影響的,那麼,對於DecorView來說,它已經是頂層view了,沒有父容器,那麼它的MeasureSpec怎麼來的呢? 
為了解決這個疑問,我們回到ViewRootImpl#PerformTraveals方法,看①號程式碼處,呼叫了getRootMeasureSpec(desiredWindowWidth,lp.width)方法,其中desiredWindowWidth就是螢幕的尺寸,並把返回結果賦值給childWidthMeasureSpec成員變數(childHeightMeasureSpec同理),因此childWidthMeasureSpec(childHeightMeasureSpec)應該儲存了DecorView的MeasureSpec,那麼我們看一下ViewRootImpl#getRootMeasureSpec方法的實現:

/**
 * @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 = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
        break;
    //省略...

    }
    return measureSpec;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

思路也很清晰,根據不同的模式來設定MeasureSpec,如果是LayoutParams.MATCH_PARENT模式,則是視窗的大小,WRAP_CONTENT模式則是大小不確定,但是不能超過視窗的大小等等。

那麼到目前為止,就已經獲得了一份DecorView的MeasureSpec,它代表著根View的規格、尺寸,在接下來的measure流程中,就是根據已獲得的根View的MeasureSpec來逐層測量各個子View。我們順著①號程式碼往下走,來到performMeasure方法,看看它做了什麼工作,ViewRootImpl#performMeasure:

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
    Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
    try {
        mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

方法很簡單,直接呼叫了mView.measure,這裡的mView就是DecorView,也就是說,從頂級View開始了測量流程,那麼我們直接進入measure流程。

measure 測量流程

ViewGroup的測量流程

由於DecorView繼承自FrameLayout,是PhoneWindow的一個內部類,而FrameLayout沒有measure方法,因此呼叫的是父類View的measure方法,我們直接看它的原始碼,View#measure

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
        boolean optical = isLayoutModeOptical(this);
        if (optical != isLayoutModeOptical(mParent)) {
        ...
        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
                widthMeasureSpec != mOldWidthMeasureSpec ||
                heightMeasureSpec != mOldHeightMeasureSpec) {
            ...
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } 
        ...
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

可以看到,它在內部呼叫了onMeasure方法,由於DecorView是FrameLayout子類,因此它實際上呼叫的是DecorView#onMeasure方法。在該方法內部,主要是進行了一些判斷,這裡不展開來看了,到最後會呼叫到super.onMeasure方法,即FrameLayout#onMeasure方法。

由於不同的ViewGroup有著不同的性質,那麼它們的onMeasure必然是不同的,因此這裡不可能把所有佈局方式的onMeasure方法都分析一遍,因此這裡選擇了FrameLayout的onMeasure方法來進行分析,其它的佈局方式讀者可以自行分析。那麼我們繼續來看看這個方法:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    //獲取當前佈局內的子View數量
    int count = getChildCount();

    //判斷當前佈局的寬高是否是match_parent模式或者指定一個精確的大小,如果是則置measureMatchParent為false.
    final boolean measureMatchParentChildren =
            MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
            MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
    mMatchParentChildren.clear();

    int maxHeight = 0;
    int maxWidth = 0;
    int childState = 0;

    //遍歷所有型別不為GONE的子View
    for (int i = 0; i < count; i++) {
        final View child = getChildAt(i);
        if (mMeasureAllChildren || child.getVisibility() != GONE) {
            //對每一個子View進行測量
            measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
            final LayoutParams lp = (LayoutParams) child.getLayoutParams();
            //尋找子View中寬高的最大者,因為如果FrameLayout是wrap_content屬性
            //那麼它的大小取決於子View中的最大者
            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());
            //如果FrameLayout是wrap_content模式,那麼往mMatchParentChildren中新增
            //寬或者高為match_parent的子View,因為該子View的最終測量大小會受到FrameLayout的最終測量大小影響
            if (measureMatchParentChildren) {
                if (lp.width == LayoutParams.MATCH_PARENT ||
                        lp.height == LayoutParams.MATCH_PARENT) {
                    mMatchParentChildren.add(child);
                }
            }
        }
    }

    // Account for padding too
    maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
    maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

    // Check against our minimum height and width
    maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
    maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

    // Check against our foreground's minimum height and width
    final 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));

    //子View中設定為match_parent的個數
    count = mMatchParentChildren.size();
    //只有FrameLayout的模式為wrap_content的時候才會執行下列語句
    if (count > 1) {
        for (int i = 0; i < count; i++) {
            final View child = mMatchParentChildren.get(i);
            final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

            //對FrameLayout的寬度規格設定,因為這會影響子View的測量
            final int childWidthMeasureSpec;

            /**
              * 如果子View的寬度是match_parent屬性,那麼對當前FrameLayout的MeasureSpec修改:
              * 把widthMeasureSpec的寬度規格修改為:總寬度 - padding - margin,這樣做的意思是:
              * 對於子Viw來說,如果要match_parent,那麼它可以覆蓋的範圍是FrameLayout的測量寬度
              * 減去padding和margin後剩下的空間。
              *
              * 以下兩點的結論,可以檢視getChildMeasureSpec()方法:
              *
              * 如果子View的寬度是一個確定的值,比如50dp,那麼FrameLayout的widthMeasureSpec的寬度規格修改為:
              * SpecSize為子View的寬度,即50dp,SpecMode為EXACTLY模式
              * 
              * 如果子View的寬度是wrap_content屬性,那麼FrameLayout的widthMeasureSpec的寬度規格修改為:
              * SpecSize為子View的寬度減去padding減去margin,SpecMode為AT_MOST模式
              */
            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);
            }
            //同理對高度進行相同的處理,這裡省略...

            //對於這部分的子View需要重新進行measure過程
            child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104

由以上的FrameLayout的onMeasure過程可以看出,它還是做了相當多的工作的,這裡簡單總結一下:首先,FrameLayout根據它的MeasureSpec來對每一個子View進行測量,即呼叫measureChildWithMargin方法,這個方法下面會詳細說明;對於每一個測量完成的子View,會尋找其中最大的寬高,那麼FrameLayout的測量寬高會受到這個子View的最大寬高的影響(wrap_content模式),接著呼叫setMeasureDimension方法,把FrameLayout的測量寬高儲存。最後則是特殊情況的處理,即當FrameLayout為wrap_content屬性時,如果其子View是match_parent屬性的話,則要重新設定FrameLayout的測量規格,然後重新對該部分View測量。

在上面提到setMeasureDimension方法,該方法用於儲存測量結果,在上面的原始碼裡面,該方法的引數接收的是resolveSizeAndState方法的返回值,那麼我們直接看View#resolveSizeAndState方法:

public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
    final int specMode = MeasureSpec.getMode(measureSpec);
    final int specSize = MeasureSpec.getSize(measureSpec);
    final int result;
    switch (specMode) {
        case MeasureSpec.AT_MOST:
            if (specSize < size) {
                result = specSize | MEASURED_STATE_TOO_SMALL;
            } else {
                result = size;
            }
            break;
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        case MeasureSpec.UNSPECIFIED:
        default:
            result = size;
    }
    return result | (childMeasuredState & MEASURED_STATE_MASK);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

可以看到該方法的思路是相當清晰的,當specMode是EXACTLY時,那麼直接返回MeasureSpec裡面的寬高規格,作為最終的測量寬高;當specMode時AT_MOST時,那麼取MeasureSpec的寬高規格和size的最小值。(注:這裡的size,對於FrameLayout來說,是其最大子View的測量寬高)。

小結:那麼到目前為止,以DecorView為切入點,把ViewGroup的測量流程詳細地分析了一遍,在ViewRootImpl#performTraversals中獲得DecorView的尺寸,然後在performMeasure方法中開始測量流程,對於不同的layout佈局有著不同的實現方式,但大體上是在onMeasure方法中,對每一個子View進行遍歷,根據ViewGroup的MeasureSpec及子View的layoutParams來確定自身的測量寬高,然後最後根據所有子View的測量寬高資訊再確定父容器的測量寬高。

那麼接下來,我們繼續分析對於一個子View來說,是怎麼進行測量的。

View的測量流程

還記得我們上面在FrameLayout測量內提到的measureChildWithMargin方法,它接收的主要引數是子View以及父容器的MeasureSpec,所以它的作用就是對子View進行測量,那麼我們直接看這個方法,ViewGroup#measureChildWithMargins:

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); // 1
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

由原始碼可知,裡面呼叫了getChildMeasureSpec方法,把父容器的MeasureSpec以及自身的layoutParams屬性傳遞進去來獲取子View的MeasureSpec,這也印證了“子View的MeasureSpec由父容器的MeasureSpec和自身的LayoutParams共同決定”這個結論。那麼,我們一起來看看ViewGroup#getChildMeasureSpec方法:

public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
    int specMode = MeasureSpec.getMode(spec);
    int specSize = MeasureSpec.getSize(spec);

    //size表示子View可用空間:父容器尺寸減去padding
    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:
       //省略..具體可自行參考原始碼
        break;

    // Parent asked to see how big we want to be
    case MeasureSpec.UNSPECIFIED:
       //省略...具體可自行參考原始碼
        break;
    }
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40

上面方法也非常容易理解,大概是根據不同的父容器的模式及子View的layoutParams來決定子View的規格尺寸模式等。那麼,這裡根據上面的邏輯,列出不同的父容器的MeasureSpec和子View的LayoutParams的組合情況下所出現的不同的子View的MeasureSpec:

子View的LayoutParams\父容器SpecMode EXACTLY AT_MOST UNSPECIFIED
精確值(dp) 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

(注:該表格呈現形式參考自《Android 開發藝術探索》 任玉剛 著)

當子View的MeasureSpec獲得後,我們返回measureChildWithMargins方法,接著就會執行①號程式碼:child.measure方法,意味著,繪製流程已經從ViewGroup轉移到子View中了,可以看到傳遞的引數正是我們剛才獲取的子View的MeasureSpec,接著會呼叫View#measure,這在上面說過了,這裡不再贅述,然後在measure方法,會呼叫onMeasure方法,當然了,對於不同型別的View,其onMeasure方法是不同的,但是對於不同的View,即使是自定義View,我們在重寫的onMeasure方法內,也一定會呼叫到View#onMeasure方法的,因此我們看看它的原始碼:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
  • 1
  • 2
  • 3
  • 4
  • 1
  • 2
  • 3
  • 4

顯然,這裡呼叫了setMeasureDimension方法,上面說過該方法的作用是設定測量寬高,而測量寬高則是從getDefaultSize中獲取,我們繼續看看這個方法View#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;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

好吧,又是類似的程式碼,根據不同模式來設定不同的測量寬高,我們直接看AT_MOST和EXACTLY模式,它直接把specSize返回了,即View在這兩種模式下的測量寬高直接取決於specSize規格。也即是說,對於一個直接繼承自View的自定義View來說,它的wrap_content和match_parent屬性的效果是一樣的,因此如果要實現自定義View的wrap_content,則要重寫onMeasure方法,對wrap_content屬性進行處理。 
接著,我們看UNSPECIFIED模式,這個模式可能比較少見,一般用於系統內部測量,它直接返回的是size,而不是specSize,那麼size從哪裡來的呢?再往上看一層,它來自於getSuggestedMinimumWidth()或getSuggestedMinimumHeight(),我們選取其中一個方法,看看原始碼,View#getSuggestedMinimumWidth

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

從以上邏輯可以看出,當View沒有設定背景的時候,返回mMinWidth,該值對應於android:minWidth屬性;如果設定了背景,那麼返回mMinWidth和mBackground.getMinimumWidth中的最大值。那麼mBackground.getMinimumWidth又是什麼呢?其實它代表了背景的原始寬度,比如對於一個Bitmap來說,它的原始寬度就是圖片的尺寸。到此,子View的測量流程也完成了。

總結

這裡簡單概括一下整個流程:測量始於DecorView,通過不斷的遍歷子View的measure方法,根據ViewGroup的MeasureSpec及子View的LayoutParams來決定子View的MeasureSpec,進一步獲取子View的測量寬高,然後逐層返回,不斷儲存ViewGroup的測量寬高。

從文章開始到現在,View的測量流程已經全部分析完畢,View的measure流程是三大流程中最複雜的一個流程,其中的MeasureSpec貫穿了整個測量流程,佔有非常重要的地位,希望讀者仔細體會這個流程,最後希望這篇文章能幫助你對View的測量流程有進一步的瞭解,謝謝閱讀。

轉自:http://blog.csdn.net/a553181867/article/details/51494058

相關文章