FrameWork学习之二-Android UI绘制流程详解

一、 从ActivityThread到View绘制流程图,如下

UI的具体绘制流程.jpg

二、 Activity oncreate setContent加载xml布局过程

1.Activity.class --> setContentView
2.PhoneWindow.class --> setContentView -->installDecor() 476行

  1. PhoneWindow.class -->generateDecor 2338行
    4.PhoneWindow.class -->generateLayout 2359行
    5.PhoneWindow.class -->mDecor.onResourcesLoaded 2630行
    最外层DecorView,然后添加根布局screen_simple.xml, 返回@android:id/content 根布局
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">
    <ViewStub android:id="@+id/action_mode_bar_stub"
              android:inflatedId="@+id/action_mode_bar"
              android:layout="@layout/action_mode_bar"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:theme="?attr/actionBarTheme" />
    <FrameLayout
         android:id="@android:id/content"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:foregroundInsidePadding="false"
         android:foregroundGravity="fill_horizontal|top"
         android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>

6.初始化完父容器mContentParent,在PhoneWindow setContent()里mLayoutInflater.inflate(layoutResID, mContentParent);
加载解析xml布局,然后添加到mContentParent里。
7.LayoutInflater.class -->inflate

三、 Activity UI开始绘制是在onResume,并不是onCreate时

  1. ActivityTread --> handleResumeActivity 4468行
  2. handleResumeActivity --> wm.addView(decor, l); 4535行
    3.WindowManagerImpl --> addView 107行
    4.WindowManagerGlobal --> addView 331行
  3. addView --> root.setView(view, wparams, panelParentView, userId); 409行
    6.ViewRootImpl --> setView 919行
  4. ViewRootImpl --> requestLayout 1604行
  5. ViewRootImpl --> scheduleTraversals 1923行
  6. ViewRootImpl --> doTraversal 1943行
  7. ViewRootImpl --> performTraversals 2332行
  8. performTraversals --> performMeasure 2906行 --> mView.measure(childWidthMeasureSpec, childHeightMeasureSpec) --> onMeasure();
  9. performTraversals --> performLayout 2938行 --> host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight()) --> onLayout();
  10. performTraversals --> performDraw 3099行 --> onDraw();

四、 View测量measure

1.在学习view测量之前,我们先了解下MeasureSpec对象, 通过MeasureSpec.getMode()可获取测量模式, MeasureSpec.getSize()可获取测量大小

2.MeasureSpec的三种测量模式


image.png

3.为了深入了解,接下来我们讲解下MeasureSpec是 如何运算
Java中定义MeasureSpec 是一个int类型,4个字节 4x8 =32位,前两位为MeasureSpec的Mode类型,后面30放置MeasureSpec的size大小

我们以MeasureSpec Mode = AT_MOST, MeasureSpec size = 1080为例

public static final int AT_MOST     = 2 << MODE_SHIFT
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK  = 0x3 << MODE_SHIFT

AT_MOST值为2,十进制2转成二进制 为10, 然后左移MODE_SHIFT 30位
结果为 10 0000000000 0000000000 0000000000
MeasureSpec size 是1080,转成二进制10000111000,补全32位得到结果
00 0000000000 0000000001 0000111000

int MeasureSpec = makeMeasureSpec(size, mode);

        public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
                                          @MeasureSpecMode int mode) {
            if (sUseBrokenMakeMeasureSpec) {
                return size + mode;
            } else {
                return (size & ~MODE_MASK) | (mode & MODE_MASK);
            }
        }

MODE_MASK = 11 0000000000 0000000000 0000000000
~MODE_MASK =00 1111111111 1111111111 1111111111

size & ~MODE_MASK
00 0000000000 0000000001 0000111000 &
00 1111111111 1111111111 1111111111
=
00 0000000000 0000000001 0000111000

mode & MODE_MASK
10 0000000000 0000000000 0000000000 &
11 0000000000 0000000000 0000000000
=
10 0000000000 0000000000 0000000000

(size & ~MODE_MASK) | (mode & MODE_MASK)
00 0000000000 0000000001 0000111000 |
10 0000000000 0000000000 0000000000
=
10 0000000000 0000000001 0000111000
int MeasureSpec = makeMeasureSpec(1080, MeasureSpec.AT_MOST) =
10 0000000000 0000000001 0000111000

java二进制运算符


image.png

4.View测量onMeasure,不同view测量规则不一样,我们以FrameLayout为例
FrameLayout是帧布局,他的子view是一个个重叠放置,所以它的大小取解于最大子View的大小maxHeight,maxWidth


        int maxHeight = 0;
        int maxWidth = 0;
        int childState = 0;

        for (int i = 0; i < count; i++) {
            final View child = getChildAt(i);
            if (mMeasureAllChildren || child.getVisibility() != GONE) {
                measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
                final LayoutParams lp = (LayoutParams) child.getLayoutParams();
                maxWidth = Math.max(maxWidth,
                        child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
                maxHeight = Math.max(maxHeight,
                        child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
                childState = combineMeasuredStates(childState, child.getMeasuredState());
                if (measureMatchParentChildren) {
                    if (lp.width == LayoutParams.MATCH_PARENT ||
                            lp.height == LayoutParams.MATCH_PARENT) {
                        mMatchParentChildren.add(child);
                    }
                }
            }
        }

measureChildWithMargins测量出子view大小-->getChildMeasureSpec

    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:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = 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;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

如果父类mode是EXACTLY精确
1.如果子类childDimension>0,则子类大小resultSize = childDimension,并且类型是精确
2.如果子类childDimension为LayoutParams.MATCH_PARENT,则子类大小resultSize=父类大小size,并且类型是精确
3.如果子类childDimension为LayoutParams.WRAP_CONTENT,则子类大小resultSize最大为父类大小size,类型是At_MOST

后面几种类型依此类推,不再详解

五、 View测量onLayout

我们还是以简单的FrameLayout为例

1.布局子view

image.png

childView左起点childLeft = parentLeft + lp.leftMargin childRight=childLeft+width
childView顶部起点childTop = parentTop + lp.topMargin childBottom= childTop +height


image.png

六、 View测量onDraw

    public void draw(Canvas canvas) {
        final int privateFlags = mPrivateFlags;
        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

        /*
         * 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)
         *      7. If necessary, draw the default focus highlight
         */

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

        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
            onDraw(canvas);

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

            drawAutofilledHighlight(canvas);

            // Overlay is part of the content and draws beneath Foreground
            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // Step 6, draw decorations (foreground, scrollbars)
            onDrawForeground(canvas);

            // Step 7, draw the default focus highlight
            drawDefaultFocusHighlight(canvas);

            if (isShowingLayoutBounds()) {
                debugDrawFocus(canvas);
            }

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

① 绘制 View 的背景
② 绘制 View 的内容
③ 绘制子 View
④ 绘制装饰(渐变框、滑动条、前景等)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,099评论 6 492
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,828评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 158,540评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,848评论 1 285
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,971评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,132评论 1 291
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,193评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,934评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,376评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,687评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,846评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,537评论 4 335
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,175评论 3 317
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,887评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,134评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,674评论 2 362
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,741评论 2 351

推荐阅读更多精彩内容