Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

從源碼看 Android UI 三大流程:measure、layout、draw 到底做了什麼

編輯:關於 Android 程式設計

ViewRootImpl 的 performTraversals() 方法很長,但骨幹只有三步:performMeasure()、performLayout()、performDraw()。以下逐一拆解。

一、Measure:算出「我想要的尺寸」

performMeasure() 直接呼叫根節點的 measure()。這裡的 mView 就是 PhoneWindow 的 mDecor,也就是一個 Activity 對應的那棵視圖樹根。

而 View.measure() 會呼叫 onMeasure(),後者的預設實作只是呼叫 setMeasuredDimension(),為 mMeasuredWidth 與 mMeasuredHeight 兩個成員賦值。看似簡單,但結論很關鍵:

onMeasure() 的作用,是設定「自己期望的大小」。

以 TextView 為例,它要顯示一段文字,就得算出自己需要多少寬高。這取決於兩組資訊:一是你在 XML 或程式碼設定的 layout_width / layout_height(可能是 match_parent、wrap_content,或 30dp 這種具體值),二是父容器給它多少可用空間。

常理上這需要四個參數,但 Android 只用兩個 int 就解決了——widthMeasureSpec 與 heightMeasureSpec。做法是把 32 位元整數的最高 2 位當 mode、低 30 位當 size。mode 有三種:

  • EXACTLY:父容器給了確定值,對應 match_parent 或明確數值。
  • AT_MOST:上限就是這個值,對應 wrap_content。
  • UNSPECIFIED:不限制,通常出現在 ScrollView 這類需要子層自行決定的場景。

低 30 位的 size 代表「目前可用的最大寬高」。例如父容器設了四边 10px 的 padding,那麼傳給子 View 的可用尺寸就是(螢幕寬 - 20,螢幕高 - 20)。

取出這兩個資訊要用 MeasureSpec.getMode() 與 MeasureSpec.getSize(),不需要自己做位移運算。onMeasure 結束後,外部就能用 getMeasuredWidth() / getMeasuredHeight() 取得結果。

總結四點:

  1. onMeasure() 由 measure() 呼叫。
  2. 它計算當前 View 自身需要多大,依據是設定的寬高參數與父容器給的空間,最終不應超出後者。
  3. 結束前必須呼叫 setMeasuredDimension(),注意這裡傳入的兩個 int 是純數值,整個 32 位都表示大小,與 MeasureSpec 的編碼方式不同。
  4. 完成後用 getMeasuredWidth / getMeasuredHeight 取得。

接著 measure 一路遞迴到所有子 View,再一路回棧,全部量完才進入 layout。

二、Layout:決定「實際畫在哪、畫多大」

performLayout() 呼叫根 View 的 layout(),其四個參數 left、top、right、bottom 都是相對於父容器的值:left 是自身左邊到父容器左邊的距離,top 同理,right 等於 left 加上寬度。合起來就是「四條邊到父容器左上角」的距離。

layout() 內部最關鍵的一步是 setFrame()。注意它算寬度用的是 right - left,而不是 mMeasuredWidth。這不是 bug,而是設計:Frame 代表這個 View 真正渲染到螢幕上的矩形區域,由四個邊界值決定。

舉個例子:父容器寬 500、padding 為 0,第一個子 View 佔了 300px,第二個也想要 300px。流程是這樣的——父容器先遍歷子 View 呼叫 onMeasure,大家都知道各自想要多大;接著父容器在 onLayout 中遍歷呼叫子 View 的 layout(),此時它已經知道只剩 200px,於是給第二個子 View 傳入收斂後的四邊值,第二個子 View 的 Frame 寬度就只會是 200px,不會溢出。

由此得到一個重要事實:

measure 出來的是「期望尺寸」,真正顯示的位置與大小由 layout 決定。left / top 決定位置,right / bottom 決定渲染範圍。

View 本身的 onLayout() 是空實作(因為它沒有子 View),真正的邏輯在各個 ViewGroup 裡。所以自訂 ViewGroup 時,你要做的就是算好每個子 View 的 left、top、right、bottom,然後呼叫它們的 layout()。

三、Draw:把內容畫上去

draw 流程最終是呼叫 Canvas 的繪圖介面,更底層的實作在 native 層。以 TextView 為例:它依文字大小、顏色等屬性設定 Paint 物件,然後在 onDraw() 中用這個 Paint 把文字畫出來。

值得注意的一點是:onDraw 每次都從頭到尾重畫一遍。當你呼叫 setText() 這類方法時,它會先更新自身屬性,再請求重繪,於是 onDraw 又被完整呼叫一次。它不是「只畫改變的那部分」,而是把目前所有屬性都重新考慮進去。

四、自己寫一個 LinearLayout 驗證理解

下面這個自製容器只實作了垂直布局,但足以把 measure 與 layout 的關係走一遍:

public class KLinearLayout extends ViewGroup {

    public static final byte ORITENTATION_VERTICAL = 0x1;
    public static final byte ORITENTATION_HORIZONTAL = 0x0;

    private int mOritentation = ORITENTATION_HORIZONTAL;
    private int mWidth;
    private int mHeight;

    public KLinearLayout(Context context) {
        super(context);
    }

    public void setOritentation(byte oritentation) {
        mOritentation = oritentation;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mOritentation == ORITENTATION_HORIZONTAL) {
            measureHorizontal(widthMeasureSpec, heightMeasureSpec);
        } else {
            measureVertical(widthMeasureSpec, heightMeasureSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mOritentation == ORITENTATION_HORIZONTAL) {
            layoutHorizontal(l, t, r, b);
        } else {
            layoutVertical(l, t, r, b);
        }
    }

    /** 垂直測量 */
    private void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        // 已使用高度,同時也是所有子 View 需要的高度總和
        int heightUsed = 0;
        View childTemp = null;

        for (int index = 0; index < getChildCount(); index++) {
            childTemp = getChildAt(index);
            measureChildWithMargins(childTemp, widthMeasureSpec, 0,
                    heightMeasureSpec, heightUsed);

            LinearLayout.LayoutParams childLp =
                    (LinearLayout.LayoutParams) childTemp.getLayoutParams();

            heightUsed = heightUsed + childTemp.getMeasuredHeight()
                    + childLp.topMargin + childLp.bottomMargin;

            // 垂直排列時,寬度取所有子 View 的最大值
            mWidth = Math.max(mWidth, childTemp.getMeasuredWidth()
                    + childLp.leftMargin + childLp.rightMargin);
        }

        mWidth = mWidth + getPaddingLeft() + getPaddingRight();

        switch (widthMode) {
            case MeasureSpec.AT_MOST:      // wrap_content:取小
                mWidth = Math.min(widthSize, mWidth);
                break;
            case MeasureSpec.EXACTLY:      // match_parent:聽父容器的
                mWidth = widthSize;
                break;
            case MeasureSpec.UNSPECIFIED:
                break;
        }

        mHeight = heightUsed + getPaddingTop() + getPaddingBottom();

        switch (heightMode) {
            case MeasureSpec.AT_MOST:
                mHeight = Math.min(heightSize, mHeight);
                break;
            case MeasureSpec.EXACTLY:
                mHeight = heightSize;
                break;
            case MeasureSpec.UNSPECIFIED:
                break;
        }

        setMeasuredDimension(mWidth, mHeight);
    }

    private void measureHorizontal(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(100, 100);
    }

    /** 垂直布局 */
    private void layoutVertical(int l, int t, int r, int b) {
        int avaliableLeft = getPaddingLeft();
        int avaliableTop = getPaddingTop();
        View childTemp = null;

        for (int i = 0; i < getChildCount(); i++) {
            childTemp = getChildAt(i);
            LinearLayout.LayoutParams childLp =
                    (LinearLayout.LayoutParams) childTemp.getLayoutParams();

            // layout() 會確切限制 View 實際顯示的大小與位置
            childTemp.layout(
                    avaliableLeft + childLp.leftMargin,
                    avaliableTop + childLp.topMargin,
                    childTemp.getMeasuredWidth() + avaliableLeft + childLp.rightMargin,
                    childTemp.getMeasuredHeight() + avaliableTop + childLp.bottomMargin);

            avaliableTop = avaliableTop + childTemp.getMeasuredHeight()
                    + childLp.topMargin + childLp.bottomMargin;
        }
    }

    private void layoutHorizontal(int l, int t, int r, int b) { }
}

使用方式很直觀:new 出來、設定 LayoutParams 與 padding、指定方向,然後 addView 一堆 TextView。

KLinearLayout myLinearLayout = new KLinearLayout(this);
myLinearLayout.setLayoutParams(new LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
myLinearLayout.setPadding(10, 20, 30, 40);
myLinearLayout.setOritentation(KLinearLayout.ORITENTATION_VERTICAL);
root.addView(myLinearLayout);

TextView tv = new TextView(this);
tv.setText("abcd哈哈你好");
tv.setTextSize(50);
LayoutParams lp = new LayoutParams(
        LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
lp.setMargins(10, 10, 10, 10);
tv.setLayoutParams(lp);
myLinearLayout.addView(tv);

一句話總結

measure 回答「我想要多大」,layout 回答「我最終在哪、多大」,draw 負責「照目前屬性完整重畫一次」。搞懂這三者的分工,客製化 View 時大部分奇怪的顯示問題都能定位。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved