探索源碼, View的工作原理

歡迎Follow我的GitHub, 關注我的簡書, 博客目錄.

View

本文的合集已經編著成書,高級Android開發強化實戰,歡迎各位讀友的建議和指導。在京東即可購買:https://item.jd.com/12385680.html

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調用onDrawdispatchDraw. Measure中, 調用getMeasuredHeightgetMeasuredWidth獲取繪制好的高度與寬度; Layout中, 調用getHeightgetWidth獲取布局好的高度與寬度. 注意因時機不同, 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_contentmatch_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的三大流程, 有利于提升程序設計理念, 與開發質量.

That's all! Enjoy it!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,646評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,595評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,560評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,035評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,814評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,224評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,301評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,444評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,988評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,804評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,998評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,544評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,237評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,665評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,927評論 1 287
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,706評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,993評論 2 374

推薦閱讀更多精彩內容