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

Android View 繪製流程完整解析:measure、layout 與 draw

編輯:關於 Android 程式設計

一、View 樹的繪圖流程

當 Activity 取得焦點時,系統會請求繪製版面配置。這個請求由 Android Framework 處理,繪製從根節點開始,對整棵版面樹進行 measure 與 draw。

整個流程在 ViewRoot.java 的 performTraversals() 函式中展開。這個函式做的事可以概括為三個判斷:是否需要重新計算檢視大小(measure)、是否需要重新安置檢視位置(layout)、是否需要重繪(draw)。

函式呼叫鏈如下:

圖片來源:Arpit Mathur

這裡有個容易搞錯的關鍵:使用者主動呼叫 request,只會觸發 measure 與 layout,不會執行 draw。

二、measure 與 layout 的概念

從整體來看,這兩個步驟的執行方式如下:

樹的遍歷是有序的:由父檢視到子檢視,每個 ViewGroup 負責測繪它所有的子檢視,而最底層的 View 則負責測繪自身。

具體分析

  • measure 由 measure(int, int) 發起,由上而下有序測量。過程結束時,每個檢視都存好了自己的尺寸與測量規格。
  • layout 由 layout(int, int, int, int) 發起,同樣自上而下遍歷。每個父檢視依據 measure 得到的尺寸來擺放自己的子檢視。

measure 過程會為一個 View 及其所有子節點的 mMeasuredWidth 與 mMeasuredHeight 賦值,可透過 getMeasuredWidth() 與 getMeasuredHeight() 取得。這兩個值必須落在父檢視約束的範圍內,才能確保所有父檢視都接收得到子檢視的測量結果。

如果子檢視對 measure 出來的大小不滿意,父檢視會介入並設定測量規則進行第二次 measure。例如父檢視可以先以未指定的 dimension 測量每個子檢視,若最終發現子檢視的未約束尺寸太大或太小,就換一個確切大小再測一次。這也是 onMeasure() 有可能被呼叫多次的原因。

measure 過程傳遞尺寸的兩個類別

ViewGroup.LayoutParams

這是我們最常見的類別,用來指定檢視的高與寬。對於每個檢視的 height 與 width,有三種選擇:

  • 具體數值,例如 100dp
  • MATCH_PARENT:子檢視希望與父檢視一樣大(不含 padding)
  • WRAP_CONTENT:檢視大小剛好能包裹內容(含 padding)

每個 ViewGroup 子類都有對應的 LayoutParams 子類,例如 RelativeLayout 對應 RelativeLayout.LayoutParams。呼叫 view.getLayoutParams() 得到的其實就是其所在父檢視類型的 LayoutParams——若 View 的父容器是 RelativeLayout,那麼得到的就是 RelativeLayout.LayoutParams。搞錯這點,強轉時就會噴 ClassCastException。

MeasureSpec

測量規格,包含「測量要求」與「尺寸」兩部分資訊,由 32 位元整數打包而成(高 2 位存模式,低 30 位存尺寸)。共三種模式:

  • UNSPECIFIED:父檢視不對子檢視做任何約束,它可以達到期望的任意尺寸。ListView、ScrollView 內部會用到,自訂 View 時較少碰。
  • EXACTLY:父檢視為子檢視指定確切尺寸,子檢視無論期望多大都必須在該邊界內。對應 match_parent 或具體數值。父容器可用 MeasureSpec.getSize(measureSpec) 直接取得尺寸。
  • AT_MOST:父檢視指定一個最大尺寸,子檢視必須確保自身內容能適應這個範圍。對應 wrap_content。這種模式下父容器無法確定子 View 的尺寸,只能由子檢視自行計算——這正是自訂檢視必須實作測量邏輯的場景。

三、measure 核心方法

  • measure(int widthMeasureSpec, int heightMeasureSpec)
    定義在 View.java 中,為 final 修飾,不可覆寫。但它最終會回呼 View / ViewGroup 的 onMeasure(),所以自訂檢視時只要覆寫 onMeasure() 即可。
  • onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    自訂檢視實作測量邏輯的地方。參數是父檢視對子檢視的寬高要求。要做的是依據這兩個 Spec 計算出自己的寬與高,不同模式處理方式不同。
  • setMeasuredDimension()
    測量階段的終極方法,在 onMeasure() 中呼叫,把計算結果傳入,測量階段即結束。這是必須呼叫的方法,否則會拋出 IllegalStateException。自訂檢視時不必理會系統複雜的測量過程,只要呼叫它設定依 MeasureSpec 算出的尺寸即可,可以參考 ViewPagerIndicator 的 onMeasure 實作。

ViewGroup 如何測量子檢視

下圖是 measureChildren(int widthMeasureSpec, int heightMeasureSpec) 的呼叫流程:

/**
 * 請求所有子 View 去 measure 自己。
 * 需要考量的部分:對子 View 的測繪要求 MeasureSpec,以及自身的 padding。
 * 這裡會跳過所有 GONE 狀態的子 View。
 * 最繁重的工作在 getChildMeasureSpec 中處理。
 */
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
    final int size = mChildrenCount;
    final View[] children = mChildren;
    for (int i = 0; i < size; ++i) {
        final View child = children[i];
        if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
        }
    }
}

protected void measureChild(View child,
        int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
    final LayoutParams lp = child.getLayoutParams();

    final int childWidthMeasureSpec = getChildMeasureSpec(
            parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight,
            lp.width);

    final int childHeightMeasureSpec = getChildMeasureSpec(
            parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom,
            lp.height);

    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

/**
 * measureChildren 中最繁重的部分:為每個 ChildView 算出自己的 MeasureSpec。
 * 目標是把 ChildView 的 MeasureSpec 與 LayoutParams 結合,得到最合適的結果。
 */
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
    // ... 依據子檢視的測量要求與大小建立 MeasureSpec
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

/** measure 為 final,最終一定回呼 onMeasure */
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
    // ...
    onMeasure(widthMeasureSpec, heightMeasureSpec);
    // ...
}

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

四、layout 相關概念與核心方法

首先要明確:子檢視的具體位置都是相對於父檢視而言的。

View 的 onLayout 是空實作,而 ViewGroup 的 onLayout 是 abstract 的。因此自訂的 View 若繼承 ViewGroup,就必須實作 onLayout。

layout 過程中,子檢視會呼叫 getMeasuredWidth() 與 getMeasuredHeight() 取得 measure 階段的結果作為自身寬高,然後呼叫每個子檢視的 layout(l, t, r, b) 來確定它在父檢視中的位置。

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

/** 遍歷所有子 View,為其設定相對父檢視的座標 */
void layoutVertical(int left, int top, int right, int bottom) {
    for (int i = 0; i < count; i++) {
        final View child = getVirtualChildAt(i);
        if (child == null) {
            childTop += measureNullChild(i);
        } else if (child.getVisibility() != GONE) {
            final int childWidth = child.getMeasuredWidth();   // measure 階段確定的寬
            final int childHeight = child.getMeasuredHeight(); // measure 階段確定的高
            // ... 計算 childLeft、childTop
            setChildFrame(child, childLeft, childTop + getLocationOffset(child),
                    childWidth, childHeight);
        }
    }
}

private void setChildFrame(View child, int left, int top, int width, int height) {
    child.layout(left, top, left + width, top + height);
}

// View.java
public void layout(int l, int t, int r, int b) {
    // ...
    setFrame(l, t, r, b);
}

/** 為該子 View 設定相對其父檢視的座標 */
protected boolean setFrame(int left, int top, int right, int bottom) {
    // ...
}

五、draw 相關概念與核心方法

  • View.draw(Canvas canvas)
    ViewGroup 並未覆寫此方法,因此所有檢視最終都會調用 View 的 draw 進行繪製。自訂檢視不應覆寫它,而應覆寫 onDraw(Canvas)。若確實需要覆寫,請先呼叫 super.draw(canvas) 完成系統繪製,再做自訂處理。
  • View.onDraw()
    預設是空實作,是自訂繪製時要覆寫的方法,用來畫出自身內容。
  • dispatchDraw()
    發起對子檢視的繪製。View 中是空實作,ViewGroup 覆寫了它以繪製子檢視。自訂 ViewGroup 時不應該覆寫 dispatchDraw。

繪製流程圖:

/**
 * Manually render this view (and all of its children) to the given Canvas.
 * The view must have already done a full layout before this function is called.
 *
 * When implementing a view, implement onDraw(android.graphics.Canvas)
 * instead of overriding this method. If you do need to override this method,
 * call the superclass version.
 */
public void draw(Canvas canvas) {

    /*
     * Draw traversal performs several drawing steps which must be executed
     * in the appropriate order:
     *
     * 1. Draw the background if needed
     * 2. If necessary, save the canvas' layers to prepare for fading
     * 3. Draw view's content
     * 4. Draw children (dispatchDraw)
     * 5. If necessary, draw the fading edges and restore layers
     * 6. Draw decorations (scrollbars for instance)
     */

    // Step 1, draw the background, if needed
    if (!dirtyOpaque) {
        drawBackground(canvas);
    }

    // skip step 2 & 5 if possible (common case)
    final int viewFlags = mViewFlags;
    if (!verticalEdges && !horizontalEdges) {

        // Step 3, draw the content
        if (!dirtyOpaque) onDraw(canvas);

        // Step 4, draw the children
        dispatchDraw(canvas);

        // Step 6, draw decorations (scrollbars)
        onDrawScrollBars(canvas);

        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }
        return;
    }

    // Step 2, save the canvas' layers ...
    // Step 3, draw the content
    if (!dirtyOpaque) onDraw(canvas);
    // Step 4, draw the children
    dispatchDraw(canvas);
    // Step 5, draw the fade effect and restore layers
    // Step 6, draw decorations (scrollbars)
    onDrawScrollBars(canvas);
}

從這段程式碼可以直接讀出一個效能優化技巧:當不需要繪製 Layer 時,第二步與第五步會被整段跳過。因此繪製時能省掉的 layer 就盡量省,可以明顯提升效率。

dispatchDraw(Canvas canvas) {
    // ...

    if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
        // 處理 ChildView 的動畫
        final boolean buildCache = !isHardwareAccelerated();
        for (int i = 0; i < childrenCount; i++) {
            final View child = children[i];
            if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
                final LayoutParams params = child.getLayoutParams();
                attachLayoutAnimationParameters(child, params, i, childrenCount);
                bindLayoutAnimation(child);
                if (cache) {
                    child.setDrawingCacheEnabled(true);
                    if (buildCache) {
                        child.buildDrawingCache(true);
                    }
                }
            }
        }
        final LayoutAnimationController controller = mLayoutAnimationController;
        if (controller.willOverlap()) {
            mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
        }
        controller.start();
    }

    // 繪製 ChildView —— 只繪製 VISIBLE 狀態的檢視
    for (int i = 0; i < childrenCount; i++) {
        int childIndex = customOrder
                ? getChildDrawingOrder(childrenCount, i) : i;
        final View child = (preorderedList == null)
                ? children[childIndex] : preorderedList.get(childIndex);
        if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE
                || child.getAnimation() != null) {
            more |= drawChild(canvas, child, drawingTime);
        }
    }
    // ...
}

protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
    return child.draw(canvas, this, drawingTime);
}
  • drawChild(canvas, this, drawingTime)
    直接調用 View 的 child.draw(canvas, this, drawingTime)。文件明確說明:除了被 ViewGroup.drawChild() 呼叫外,你不應該在其他任何地方覆寫或調用該方法。而 View.draw(Canvas) 才是自訂檢視中可以覆寫的方法。從參數可以看到 child.draw(canvas, this, drawingTime) 處理了與父檢視相關的邏輯,但最終的繪製仍落在 View.draw(Canvas)。
  • invalidate()
    請求重繪 View 樹,即觸發 draw 過程。若檢視大小沒變化,不會呼叫 layout(),且只會繪製那些呼叫了 invalidate() 的 View。
  • requestLayout()
    版面變化時(方向、尺寸變更)會呼叫。自訂檢視中若某些情況下希望重新測量尺寸,應手動呼叫它。它會觸發 measure() 與 layout(),但不會進行 draw。

重點回顧

  1. 繪製從根節點開始,交給 ViewRoot.performTraversals() 統一決策。
  2. measure 由父到子傳遞 MeasureSpec,子檢視負責在 onMeasure() 中算出尺寸並呼叫 setMeasuredDimension()。
  3. layout 依 measure 結果擺放子檢視,自訂 ViewGroup 必須實作 onLayout()。
  4. draw 分六步,自訂檢視只覆寫 onDraw(),ViewGroup 不要覆寫 dispatchDraw()。
  5. invalidate() 只重繪,requestLayout() 只重測與重排——搞混這兩個,是效能問題的常見來源。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved