Android UI繪製流程之測量篇

經過前一片前奏的分析,我們知道從ViewRootImpl的performTraversals方法正式進入View的測量、佈局、繪製流程。本文着重分析View的measure流程。直接上代碼吧

frameworks/base/core/java/android/view/ViewRootImpl.java

private void performTraversals() {
    ...
    if (!mStopped || mReportNextDraw) {
        boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
            (relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
                if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
                        || mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
                        updatedConfiguration) {
                    // 註釋2
                    int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
                    int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);

                    if (DEBUG_LAYOUT) Log.v(mTag, "Ooops, something changed!  mWidth="
                            + mWidth + " measuredWidth=" + host.getMeasuredWidth()
                            + " mHeight=" + mHeight
                            + " measuredHeight=" + host.getMeasuredHeight()
                            + " coveredInsetsChanged=" + contentInsetsChanged);

                    // 註釋1
                    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
    				...
                }
        ...
    }
    ...   
}

在performTraversals方法中找到測量相關的邏輯代碼註釋1處的performMeasure方法,根據方法的參數定位到註釋2處的代碼,顧名思義,表示寬高的“測量規格“的意思。那測量規格具體指的是什麼呢?帶着疑問進入getRootMeasureSpec方法:

frameworks/base/core/java/android/view/ViewRootImpl.java

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

這裏我們看到了MeasureSpec對象,它的作用是在measure流程中,系統將View的LayoutParams根據父容器所施加的規則轉換成對應的MeasureSpec(測量規格),然後在onMeasure中根據這個MeasureSpec來確定view的測量寬高。這是我們打開MeasureSpec源碼,在這中間我們會看到下面這幾個方法:

 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);
    }
    //...
}

MeasureSpec代表一個32位的int值,高2位代表SpecMode,表示測量模式,低30位代表SpecSize,表示在某種測量模式下的規格大小。MeasureSpec將SpecMode和SpecSize打包成一個int值來避免過多的對象內存分配,爲了方便操作,其提供了打包的方法makeMeasureSpec,SpecMode和SpecSize也是一個int值,MeasureSpec也可以通過解包的方法getMode和getSize得到原始的SpecMode和SpecSize。具體的運算就是藉助MODE_MASK這個常量來輔助實現的。

ModeMask

第一個常量ModeMask是3向左位移了30位,因爲int型以四個字節存儲,所以3的二進制在內存中存儲:
00000000 00000000 00000000 00000011
左位移30位之後:
11000000 00000000 00000000 00000000

SpecMode有三類,每一類都表示特殊的含義,如下所示。

UNSPECIFIED

父容器不對View有任何限制,要多大給多大,這種情況一般用於系統內部,表示一

種測量的狀態。

EXACTLY : 精確模式

父容器已經檢測出View所需要的精確大小,這個時候View的最終大小就是SpecSize所
指定的值。它對應於LayoutParams中的match_parent和具體的數值這兩種模式。

EXACTLY常量1在內存中存儲:
00000000 00000000 00000000 00000001
左位移30位之後:
01000000 00000000 00000000 00000000

AT_MOST :最大模式

父容器指定了一個可用大小即SpecSize,View的大小不能大於這個值,具體是什麼值
要看不同View的具體實現。它對應於LayoutParams中的wrap_content。

AT_MOST常量2在內存存儲:
00000000 00000000 00000000 00000010
左位移30位之後:
10000000 00000000 00000000 00000000

相關的計算原理分析:

符號 描述 運算規則
& 兩個位都爲1時,結果才爲1
| 兩個位都爲0時,結果才爲0
^ 異或 兩個位相同,結果爲0,相異爲1
取反 0變爲1, 1變爲0
<< 左移 二進位全部左移若干位,高位丟棄,低位補0
>> 右移 二進位全部右移若干位,對無符號數,高位補0,有符號數,各編譯器處理方法不一樣,有的補符號位(算術右移),有的補0(邏輯右移)

比如makeMeasureSpec(8, MeasureSpec.EXACTLY),

即size=8, 二進制表示爲:00000000 00000000 00000000 00001000

MeasureSpec.EXACTLY= 1 << 30

二進制表示爲:01000000 00000000 00000000 00000000

方法返回表達式 (size & ~MODE_MASK) | (mode & MODE_MASK)的值

MODE_MASK :11000000 00000000 00000000 00000000

~MODE_MASK:00111111 11111111 11111111 11111111

size & ~MODE_MASK:

​ 00000000 00000000 00000000 00001000

&

​ 00111111 11111111 11111111 11111111

=

​ 00000000 00000000 00000000 00001000

mode = MeasureSpec.EXACTLY= 1 << 30 : 01000000 00000000 00000000 00000000

mode & MODE_MASK

​ 01000000 00000000 00000000 00000000

​ &

​ 11000000 00000000 00000000 00000000

​ =

​ 01000000 00000000 00000000 00000000

(size & ~MODE_MASK) | (mode & MODE_MASK)

​ 00000000 00000000 00000000 00001000

​ |

​ 01000000 00000000 00000000 00000000

​ =

​ 01000000 00000000 00000000 00001000

measureSpec的值,二進制表示爲:01000000 00000000 00000000 00001000

再看getSize()方法:measureSpec & ~MODE_MASK

01000000 00000000 00000000 00001000

&

00111111 11111111 11111111 11111111

=

00000000 00000000 00000000 00001000

返回值二進制表示爲8

對MeasureSpec有了初步的認識後,我們再回到performTraversals方法的註釋2處的getRootMeasureSpec方法,點擊進入,我們發現參數mWindow對應參數windowSize表示窗口的寬度,lp.width對應rootDimension表示就是頂層View即DecorView佈局屬性設置的寬度。結合方法內部的switch語句,不難得出結論,對於DecorView而言,其MeasureSpec由窗口的尺寸和自身的LayoutParams來共同決定的。

再次回到源碼分析流程,進入performMeasure方法:

frameworks/base/core/java/android/view/ViewRootImpl.java

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
    if (mView == null) {
        return;
    }
    Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
    try {
        // 註釋1
        // mView表示DecorView,可進入setView查看
        mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    } finally {
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
    }
}

進入measure方法,來到了View的measure方法,我們發現它內部調用了onMeasure方法:

frameworks/base/core/java/android/view/View.java

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
    ...
    onMeasure()
    ...
}

進入View的onMea方法:

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

總體來說,performMeasure在最終調用到具體View的onMeasure方法,而我們的控件會更具自身的業務需求來重寫onMeasure方法,無論是系統的FrameLayout、LinearLayout等控件,還是我們自定義控件的時候,onMeasure的邏輯都不盡相同。這也是爲什麼ViewGroup沒有onMeasure方法,即沒有定義測量的具體過程,ViewGroup是一個抽象類,測量過程的onMeasure方法需要各個子類去具體實現,不同的ViewGroup子類有不同的佈局特性,這導致它們的測量細節各不相同,因此ViewGroup無法統一實現(onMeasure方法)。

由於前面的mView表示DecorView,而DecorView繼承FrameLayout,所以這裏以FrameLayout爲例分析ViewGroup的測量過程。進入FrameLayout的onMeasure方法:

frameworks/base/core/java/android/widget/FrameLayout.java

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

	//判斷當前佈局的寬高是否是match_parent模式或者指定一個精確的大小,如果寬高中只要有一個爲
	//wrap_content,那麼measureMatchParentChildren爲true,否則爲false
	final boolean measureMatchParentChildren =
	MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
    MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
    ...
	// 遍歷所有可見類型不爲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加上margin的大小
            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
            // 當FrameLayout爲wrap_content的時候,子View的測量大小會影響FrameLayout的測量大小
            if (measureMatchParentChildren) {
            if (lp.width == LayoutParams.MATCH_PARENT ||
            lp.height == LayoutParams.MATCH_PARENT) {
            // 滿足FrameLayout寬或高有一個爲wrap_content, 子View的寬或高有一個
            // match_parent時,將子View添加到集合
                    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));
	// 有match_parent的子View個數
    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();
			// 對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);
        }
    }
}

對於FrameLayout的測量流程詳細分析,可對照註釋進行查閱,再次總結一下,FrameLayout根據它的MeasureSpec來對每一個子View進行測量,即調用measureChildWithMargin方法,這個方法下面會詳細說明;對於每一個測量完成的子View,會尋找其中最大的寬高,那麼FrameLayout的測量寬高會受到這個子View的最大寬高的影響(wrap_content模式),接着調用setMeasureDimension方法,把FrameLayout的測量寬高保存。最後則是特殊情況的處理,即當FrameLayout爲wrap_content屬性時,如果其子View是match_parent屬性的話,則要重新設置FrameLayout的測量規格,然後重新對該部分View測量。

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

frameworks/base/core/java/android/view/View.java

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

可以看到該方法的思路是相當清晰的,當specMode是EXACTLY時,那麼直接返回MeasureSpec裏面的寬高規格,作爲最終的測量寬高;當specMode時AT_MOST時,那麼取MeasureSpec的寬高規格和size的最小值,前面也提到過,當SpecMode爲AT_MOST時,父容器指定了一個可用大小即SpecSize,View的大小不能大於這個值。

上面有提到在FrameLayout測量過程中會遍歷測量子View,調用的是measureChildWithMargins方法:

frameworks/base/core/java/android/view/ViewGroup.java

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

內部調用了getChildMeasureSpec方法,看方法的參數就明白了,把父容器的MeasureSpec以及自身的layoutParams屬性傳遞進去來獲取子View的MeasureSpe,可見普通View的MeasureSpec由父容器的MeasureSpec和自身的LayoutParams來共同決定的。在這裏我們可以看到直接又調用了子類的measure測量方法遍歷測量子View。ViewGroup那麼現在我們能得到整體的測量流程:在performTraversals開始獲得DecorView種的系統佈局的尺寸,然後在performMeasure方法中開始測量流程,對於不同的layout佈局有着不同的實現方式,但大體上是在onMeasure方法中,對每一個子View進行遍歷,根據ViewGroup的MeasureSpec及子View的layoutParams來確定自身的測量寬高,然後最後根據所有子View的測量寬高信息再確定爸爸的寬高
不斷的遍歷子View的measure方法,根據ViewGroup的MeasureSpec及子View的LayoutParams來決定子View的MeasureSpec,進一步獲取子View的測量寬高,然後逐層返回,不斷保存ViewGroup的測量寬高

總結

  • 對於DecorView,其MeasureSpec由窗口的尺寸和其自身的LayoutParams共同決定的

  • 對於普通View,其MeasureSpec由父容器的MeasureSpec和自身的LayoutParams共同決定的
    在這裏插入圖片描述

  • MeasureSpec代表一個32位的int值,高2位代表SpecMode,表示測量模式,低30位代表SpecSize,表示在某種測量模式下的規格大小。MeasureSpec將SpecMode和SpecSize打包成一個int值來避免過多的對象內存分配,爲了方便操作,其提供了打包的方法makeMeasureSpec,SpecMode和SpecSize也是一個int值,MeasureSpec也可以通過解包的方法getMode和getSize得到原始的SpecMode和SpecSize

  • SpecMode有三類

    • UNSPECIFIED :父容器不對View有任何限制,要多大給多大,這種情況一般用於系統內部,表示一 種測量的狀態。

    • EXACTLY:父容器已經檢測出View所需要的精確大小,這個時候View的最終大小就是SpecSize所 指定的值。它對應於LayoutParams中的match_parent和具體的數值這兩種模式。

    • AT_MOST:父容器指定了一個可用大小即SpecSize,View的大小不能大於這個值,具體是什麼值要看不同View的具體實現。它對應於LayoutParams中的wrap_content。

  • performMeasure中會調用measure方法,在measure方法中又會調用onMeasure方法,在onMeasure方法中則會對所有的子元素進行measure過程,這個時候measure流程就從父容器傳遞到子元素了,接着子元素就會重複父容器的measure過程,如此反覆就完成了整個View數的遍歷。

  • ViewGroup是一個抽象類,沒有具體的測量方法,其測量過程由具體的子類去實現,因爲ViewGroup的不同子類有不同的佈局特性,導致測量細節各不相同,比如FrameLayout,LinearLayout, RelativeLayout佈局特性就不同,因此它無法做統一實現。但是也有相同的部分就是,要遍歷測量子元素。ViewGroup提供了不同measureChild,measureChildWithMargins等方法供它們調用,在內部都包含了獲取子元素的MeasureSpec,執行child.measure, 遍歷測量子元素

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章