你需要知道的 Android View 的測量

guojun_fire發表於2017-02-23

上一篇我們說到了View的建立,我們先回顧一下,DecorView是應用視窗的根部View,我們在View的建立簡單來說就是對DecorView物件的建立,然後將DecorView新增到我們視窗Window物件中,在新增的過程裡,實際用到是實現WindowManager抽象類的WindowManagerImpl類WindowManagerImpl#addView方法,在addView方法中重要的兩段:

root = new ViewRootImpl(view.getContext(),display);
root.setView(view,wparams,panelParentView);複製程式碼

如程式碼中所示,ViewRoot對應介面類ViewRootImpl,引數diaplay(Window類)、view(DecorView類)。
這兩段程式碼的大概是,當DecorView物件被建立後,DecorView會被加入Window中,同時會建立ViewRootImpl物件,並將ViewRootImpl物件和DecorView建立關聯。ViewRootImpl則負責渲染檢視,最後WindowManagerService呼叫ViewRootImpl#performTraverals方法使得ViewTree開始進行View的測量、佈局、繪製工作。

private void performTraversals() {
            ...

        if (!mStopped) {
            int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);  
            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();
            }
        } 
        ...
}複製程式碼

三大階段

  • measure:測量檢視的大小。
  • layout:對檢視進行佈局,就是確定檢視的位置。
  • draw:真正開始對檢視進行繪製。

onMeasure

看回ViewRootImpl#PerformTraveals程式碼之前,我們首先來了解一下MeasureSpec,MeasureSpec類是View類的一個內部類。註釋對MeasureSpec的描述翻譯是:MeasureSpc類封裝了父View傳遞給子View的佈局(layout)要求;每個MeasureSpc例項代表寬度或者高度;MeasureSpec的值由大小與規格組成。

我們看一下MeasureSpec的原始碼:(一定要完全清楚理解的點)

 public class View implements ... {
    ···
    public static class MeasureSpec {
        private static final int MODE_SHIFT = 30;//移位位數為30
        private static final int MODE_MASK  = 0x3 << MODE_SHIFT;

        //UNSPECIFIED(未指定),父元素不對子元素施加任何束縛,子元素可以得到任意想要的大小
        //向右移位30位,其值為00 + (30位0)  , 即 0x0000(16進製表示)  
        public static final int UNSPECIFIED = 0 << MODE_SHIFT;

        //EXACTLY(精確),父元素決定子元素的確切大小,子元素將被限定在給定的邊界裡而忽略它本身大小; 
        //向右移位30位,其值為01 + (30位0)  , 即0x1000(16進製表示)
        public static final int EXACTLY     = 1 << MODE_SHIFT;

        //AT_MOST(至多),子元素至多達到指定大小的值。
        //向右移位30位,其值為02 + (30位0)  , 即0x2000(16進製表示)  
        public static final int AT_MOST     = 2 << MODE_SHIFT;

        public static int makeMeasureSpec(int size, int mode) {
            if (sUseBrokenMakeMeasureSpec) {
                return size + mode;
            } else {
                return (size & ~MODE_MASK) | (mode & MODE_MASK);
            }
        }

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

        //將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);
        }
    }
}複製程式碼

從程式碼看出MeasureSpec則儲存了該View的尺寸規格。在View的測量流程中,通過makeMeasureSpec來儲存大小規格資訊,在其他類通過getMode或getSize得到模式和寬高。

可能有很多人想不通,一個int型整數怎麼可以表示兩個東西(大小模式和大小的值),一個int型別我們知道有32位。而模式有三種,要表示三種狀態,至少得2位二進位制位。於是系統採用了最高的2位表示模式。如圖:

你需要知道的 Android View 的測量

  • 最高兩位是00的時候表示"未指定模式"。即MeasureSpec.UNSPECIFIED
  • 最高兩位是01的時候表示"'精確模式"。即MeasureSpec.EXACTLY
  • 最高兩位是11的時候表示"最大模式"。即MeasureSpec.AT_MOST

在瞭解完MeasureSpec後,我們終於可以看回ViewRootImpl#PerformTraveals程式碼了。看到getRootMeasureSpec()方法,從方法命名我們瞭解到獲取根部的MeasureSpec,回想一下,MeasureSpec的第一條就說明父View傳遞給子View的佈局要求,而我們現在是DecorView是根佈局了。那getRootMeasureSpec()方法究竟是怎麼的呢?看ViewRootImpl#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;
    }複製程式碼

方法中的引數windowSize代表是視窗的大小,rootDimension代表根部(DecorView)的尺寸。而DecorView是FrameLayout子類。故DecorView的MeasureSpec中的SpecSize為視窗大小,SpecMode的EXACTLY。因此ViewRootImpl#PerformTraveals程式碼中的childWidthMeasureSpec/childHeightMeasureSpec的值被賦值為螢幕的尺寸。

現在我們獲得了DecorView的MeasureSpec。記住它代表著DecorView的尺寸和規格。接著是執行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);
    }
}複製程式碼

程式碼很易懂,呼叫mView.measure。這裡mView是DecorView,我相信大家都能懂。還有DecorView是FrameLayout子類,FrameLayout繼承ViewGroup,那我們去ViewGroup類看measure()方法,發現ViewGroup並沒有,那就去View看(ViewGroup繼承View)。終於找到了View#measure方法:(注意是final修飾符修飾,其不能被過載)

 public class View implements ... {
    ···
    public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
        boolean optical = isLayoutModeOptical(this);
        if (optical != isLayoutModeOptical(mParent)) {
            Insets insets = getOpticalInsets();
            int oWidth  = insets.left + insets.right;
            int oHeight = insets.top  + insets.bottom;
            widthMeasureSpec  = MeasureSpec.adjust(widthMeasureSpec,  optical ? -oWidth  : oWidth);
            heightMeasureSpec = MeasureSpec.adjust(heightMeasureSpec, optical ? -oHeight : oHeight);
        }

        long key = (long) widthMeasureSpec << 32 | (long) heightMeasureSpec & 0xffffffffL;
        if (mMeasureCache == null) mMeasureCache = new LongSparseLongArray(2);

        if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
                widthMeasureSpec != mOldWidthMeasureSpec ||
                heightMeasureSpec != mOldHeightMeasureSpec) {

            mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;

            resolveRtlPropertiesIfNeeded();

            int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
                    mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } else {
                long value = mMeasureCache.valueAt(cacheIndex);
                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }

            if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
                throw new IllegalStateException("View with id " + getId() + ": "
                        + getClass().getName() + "#onMeasure() did not set the"
                        + " measured dimension by calling"
                        + " setMeasuredDimension()");
            }

            mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
        }

        mOldWidthMeasureSpec = widthMeasureSpec;
        mOldHeightMeasureSpec = heightMeasureSpec;

        mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
                (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
    }
}複製程式碼

我們把目光聚焦在onMeasure()方法,由於子類繼承父類覆寫方法的原因。我們應該看到是DecorView#onMeasure,在該方法內部,主要是進行了一些判斷,這裡不展開來看了,到最後會呼叫到super.onMeasure方法,即FrameLayout#onMeasure方法。

由於不同的ViewGroup,那麼它們的onMeasure()都是不一樣的。就比如我們自定義View都覆寫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());
        }
        //所有的子View測量之後,經過一系類的計算之後通過setMeasuredDimension設定自己的寬高
        //對於FrameLayout可能用最大的子View的大小,對於LinearLayout,可能是高度的累加。
        //儲存測量結果
        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屬性,那麼對當前子View的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);
                }
                //同理對高度進行相同的處理
                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);
                }
                //對於這部分的子View需要重新進行measure過程
                child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
            }
        }
    }複製程式碼

這部程式碼很長,但是比較好理解,簡單總結下:首先,FrameLayout根據它的MeasureSpec來對每一個子View進行測量,即呼叫measureChildWithMargin方法;對於每一個測量完成的子View,會尋找其中最大的寬高,那麼FrameLayout的測量寬高會受到這個子View的最大寬高的影響(wrap_content模式),接著呼叫setMeasureDimension方法,把FrameLayout的測量寬高儲存。

從一開始的ViewRootImpl#performTraversals中獲得DecorView的尺寸,然後在performMeasure方法中開始測量流程,對於不同的layout佈局(ViewGroup)有著不同的實現方式,但大體上是在onMeasure方法中,對每一個子View進行遍歷,根據ViewGroup的MeasureSpec及子View的layoutParams來確定自身的測量寬高,然後最後根據所有子View的測量寬高資訊再確定父容器的測量寬高。那就是說要先完成對子View的測量再進行自己的測量。

那麼接著我們繼續分析對子View是怎麼測量ViewGroup#measureChildWithMargins

    protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        // 子View的LayoutParams,你在xml的layout_width和layout_height
        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);
    }複製程式碼

從上面原始碼可知,裡面主要使用了getChildMeasureSpec方法,將父容器的MeasureSpec和自己的layoutParams屬性(內外邊距和尺寸)傳遞進去來獲取子View的MeasureSpec。我們看一下ViewGroup#getChildMeasureSpec方法:

    public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);
        //計運算元View可用空間大小
        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:
            // 子View的width或height是個精確值
            if (childDimension >= 0) {
                // 表示子View的LayoutParams指定了具體大小值
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            //子View的width或height為 MATCH_PARENT/FILL_PAREN
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                // 子View想和父View一樣大
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            //子View的width或height為 WRAP_CONTENT  
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                // 子View想自己決定其尺寸,但不能比父View大 
                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);
    }複製程式碼

因為分析DecorView我就只分析MeasureSpec.EXACTLY的,然而那部分程式碼也很容易理解。整體來說就是根據不同的父容器的模式及子View的layoutParams來決定子View的規格尺寸模式。大家可以根據下圖來理解MeasureSpec父View與子View之間的賦值規則。

你需要知道的 Android View 的測量

在子View獲取到MeasureSpec後,返回到measureChildWithMargins方法中的childWidthMeasureSpec和
childHeightMeasureSpec值。接著程式碼執行child.measure()方法。該方法的引數也是我們剛剛獲取到的子View的MeasureSpec。大家還記得我們上面分析的View#measure嗎?它是final方法,所以這裡的child.measure()方法就是呼叫回View#measure,這個View#measure方法的核心就是onMeasure(),若此時的子View為ViewGroup的子類,便會呼叫相應容器類的onMeasure()方法,其他容器ViewGroup的onMeasure()方法與FrameLayout的onMeasure()方法執行過程相似,都是要遞迴子View測量。那麼我們先放一下不繼續分析,後面再回來說這個問題。

我們回到FrameLayout的onMeasure()方法中,當遞迴執行完對子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) {
                    // 父View給定的最大尺寸小於完全顯示內容所需尺寸
                    // 則在測量結果上加上MEASURED_STATE_TOO_SMALL
                    result = specSize | MEASURED_STATE_TOO_SMALL;
                } else {
                    result = size;
                }
                break;
            case MeasureSpec.EXACTLY:
                // 若specMode為EXACTLY,則不考慮size,result直接賦值為specSize
                result = specSize;
                break;
            case MeasureSpec.UNSPECIFIED:
            default:
                result = size;
        }
        return result | (childMeasuredState & MEASURED_STATE_MASK);
    }複製程式碼

上面的程式碼較為清晰易懂我們就不重複講解。我們整體來說,是先遞迴測量完子View,然後將計算的測量寬高儲存。接著說回View的onMeasure()問題,之前我們可以看出View#measure方法是final修飾的,然而它的核心方法裡頭是onMeasure(),對於不同的View有著不同的實現方式,即使是我們自定義View,也會呼叫View#onMeasure方法,所以我們也看看它裡面的實現過程:

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
    }複製程式碼

原始碼很清晰,這裡呼叫了setMeasureDimension方法,上面說過該方法的作用是設定測量寬高,而測量寬高則是從getDefaultSize中獲取,我們繼續看看這個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模式,它直接把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());
    }複製程式碼

當View沒有設定背景的時候,返回mMinWidth,該值對應於android:minWidth屬性;如果設定了背景,那麼返回mMinWidth和mBackground.getMinimumWidth中的最大值。那麼mBackground.getMinimumWidth又是什麼呢?其實它代表了背景的原始寬度,比如對於一個Bitmap來說,它的原始寬度就是圖片的尺寸。

我們的View的測量就基本到這來了,我們總結一下:測量從ViewRootImpl#performTraverals開始,首先獲取到DecorView根佈局的MeasureSpec,然後開始測量工作,通過不斷的遍歷子View的measure方法,根據ViewGroup的MeasureSpec及子View的LayoutParams來決定子View的MeasureSpec,進一步獲取子View的測量寬高,然後逐層返回,不斷儲存ViewGroup的測量寬高。

我們測量的工作完成了,我們可以看回ViewRootImpl#performTraverals方法,接著下一篇我們是佈局工作。

相關文章