探索源码, 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阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容