梳理 Android 源碼中 View 的工作原理

GusGomes 8年前發布 | 7K 次閱讀 安卓開發 Android開發 移動開發

在View的工作過程中, 執行三大流程完成顯示, 測量(measure)流程, 布局(layout)流程, 繪制(draw)流程. 從 performTraversals 方法開始, 測量(measure) View的高度(Height)與寬度(Width), 布局(layout) View在父容器中的位置, 繪制(draw) View在屏幕上.

通過源碼, 循序漸進, 解析View的工作原理和三大流程.

ViewRoot

ViewRoot連結 WindowManagerDecorView , 調用流程 performTraversals , 并依次調用 performMeasure , performLayout , performDraw .

Measure調用 onMeasure , Layout調用 onLayout , Draw調用 onDraw 與 dispatchDraw . Measure中, 調用 getMeasuredHeight 與 getMeasuredWidth 獲取繪制好的高度與寬度; Layout中, 調用 getHeight 與 getWidth 獲取布局好的高度與寬度. 注意 因時機不同, Measure的度量可能不同于Layout的度量.

Measure與Layout使用onMeasure與onLayout遍歷調用子View的方法. Draw使用onDraw繪制View本身, 使用onDispatch繪制子View.

DecorView

DecorView是頂層View, 即FrameLayout, 其中包含豎直方向的LinearLayout, 標題 titlebar , 內容 android.R.id.content . 獲取 setContentView 的布局的方法.

ViewGroup content = (ViewGroup) findViewById(android.R.id.content); // 父布局
View view = content.getChildAt(0); // 內容布局

MeasureSpec

View的 MeasureSpec , MeasureSpec是32位int值, 高2位是 SpecMode , 低30位是 SpecSize , 選擇測量的模式, 設置測量的大小.

SpecMode三種類型, UNSPECIFIED 不做任何限制; EXACTLY 精確大小, 即match_parent和具體數值; AT_MOST 不能超過最大距離, 即wrap_content.

在onMeasure中, View使用MeasureSpec測量View的大小, 由父布局的 MeasureSpec 與自身的 LayoutParams 決定; DecorView是根View, 由系統的 窗口尺寸 與自身的LayoutParams決定.

父View負責繪制子View, 子View的大小由 父View的模式與大小自身的模式與大小 決定. 簡而言之, 父容器的MeasureSpec子View的LayoutParams 決定 子View的MeasureSpec .

Measure

Measure測量View的高度與寬度. View調用onMeasure完成測量; ViewGroup遍歷子View的onMeasure, 再遞歸匯總.

View

View的 measure 方法是禁止繼承的, 調用 onMeasure 方法, 自定義View通過 onMeasure 方法設置測量大小. onMeasure 方法調用 setMeasuredDimension 設置測量大小.

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

寬與高使用 getDefaultSize 獲取默認值, 參數是推薦最小值(getSuggestedMinimumX)與指定測量規格(xMeasureSpec).

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

注意 AT_MOST 模式, 使用最小寬度, 當未設置時, 使用父容器的最大值, 因此自定義View需要設置默認值, 否者 wrap_content 與 match_parent 功能相同.

參考 ViewGroup . 當子View的布局參數是WRAP_CONTENT時, 無論父View的類型, 都是父View的空閑值.

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

    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:
        // ...
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            // Child wants to determine its own size. It can't be
            // bigger than us.
            resultSize = size; // 父View空閑寬度
            resultMode = MeasureSpec.AT_MOST;
        }
        break;

    // Parent has imposed a maximum size on us
    case MeasureSpec.AT_MOST:
        // ...
        } else if (childDimension == LayoutParams.WRAP_CONTENT) {
            // Child wants to determine its own size. It can't be
            // bigger than us.
            resultSize = size; // 父View空閑寬度
            resultMode = MeasureSpec.AT_MOST;
        }
        break;
    // ...
    }
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

自定義View需要設置 wrap_content 狀態下的測量值, 可以參考 TextViewImageView .

private int mMinWidth = 256; // 指定默認最小寬度
private int mMinHeight = 256; // 指定默認最小高度

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
    if (widthSpecMode == MeasureSpec.AT_MOST
            && heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(mMinWidth, mMinHeight);
    } else if (widthSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(mMinWidth, heightSpecSize);
    } else if (heightSpecMode == MeasureSpec.AT_MOST) {
        setMeasuredDimension(widthSpecSize, mMinHeight);
    }
}

獲取建議的最小寬度, 在已設置最小寬度 android:minWidth 與背景 android:background 的最小寬度的 最大值 , 默認返回0.

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

ViewGroup

ViewGroup使用 onMeasure 繪制自己, 并遍歷子View的onMeasure遞歸繪制.

使用 measureChildren 方法繪制全部子View.

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

子View繪制使用 measureChild , 最終匯總.

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

不同的ViewGroup實現不同的onMeasure方法, 如LinearLayout, RelativeLayout, FrameLayout等.

測量值

View的onMeasure與Activity的生命周期不一致, 無法在生命周期的方法中, 獲取測量值. 測量值需要在測量完成后計算.

onWindowFocusChanged方法, 在Activity窗口獲得或失去焦點時都會被調用, 即在onResume與onPause執行時會調用, 此時, View的測量(Measure)已經完成, 獲取測量值.

private int mWidth; // 寬度
private int mHeight; // 高度

/**
 * 在Activity獲得焦點時, 獲取測量寬度與高度
 *
 * @param hasFocus 關注
 */
@Override public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if (hasFocus) {
        mWidth = getContentView().getMeasuredWidth();
        mHeight = getContentView().getMeasuredHeight();
    }
}

/**
 * 獲取Activity的ContentView
 *
 * @return ContentView
 */
private View getContentView() {
    ViewGroup view = (ViewGroup) getWindow().getDecorView();
    FrameLayout content = (FrameLayout) view.getChildAt(0);
    return content.getChildAt(0);
}

在View的 消息隊列 尾部, 獲取測量值. View的測量過程是在消息隊列中完成的, 完成全部的系統消息, 才會執行用戶消息.

private int mWidth; // 寬度
private int mHeight; // 高度

@Override protected void onResume() {
    super.onResume();
    final View view = getContentView();
    view.post(new Runnable() {
        @Override public void run() {
            mWidth = view.getMeasuredWidth();
            mHeight = view.getMeasuredHeight();
        }
    });
}

Layout

View使用 layout 確定位置, layout調用 onLayout , 在onLayout中調用子View的layout.

layout先調用setFrame確定View的四個頂點, 即left, right, top, bottom, 再調用onLayout確定子View的位置. 在onLayout中, 調用setChildFrame確定子View的四個頂點, 子View再調用layout.

在一般情況下, View的測量(Measure)寬高與布局(Layout)寬高是相同的, 確定時機不同, 測量要早于布局.

如果在View的layout中, 重新設置寬高, 則測量寬高與布局不同, 不過此類方法, 并無任何意義.

@Override public void layout(int l, int t, int r, int b) {
    super.layout(l, t, r + 256, b + 256); // 右側底部, 各加256, 無意義
}

Draw

View的繪制(Draw)過程, 首先繪制背景, 即 android:backgroud ; 其次繪制自己, 即 onDraw ; 再次繪制子View, 即 dispatchDraw ; 最后繪制頁面裝飾, 如滾動條.

public void draw(Canvas canvas) {
    // ...

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

    // Step 1, draw the background, if needed
    int saveCount;

    // 第一步, 繪制背景
    if (!dirtyOpaque) {
        drawBackground(canvas);
    }

    // skip step 2 & 5 if possible (common case)
    final int viewFlags = mViewFlags;
    boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
    boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
    if (!verticalEdges && !horizontalEdges) {
        // Step 3, draw the content
        // 第二步, 繪制自己的內容
        if (!dirtyOpaque) onDraw(canvas);

        // Step 4, draw the children
        // 第三步, 繪制子View
        dispatchDraw(canvas);

        // Step 6, draw decorations (scrollbars)
        // 第四步, 繪制裝飾
        onDrawScrollBars(canvas);

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

        // we're done...
        return;
    }
    // ...
}

關注源碼的繪制 draw 流程: drawBackground -> onDraw -> dispatchDraw -> onDrawScrollBars

View的工作原理來源于三大流程, 測量(measure)流程, 布局(layout)流程, 繪制(draw)流程. 通過源碼理解View的三大流程, 有利于提升程序設計理念, 與開發質量.

 

 

來自:http://www.jianshu.com/p/17b372ef3f41

 

 本文由用戶 GusGomes 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!