04.源码阅读(setContentView-api26)

关键词:PhoneWindow DecorView

在调用setContentView方法设置布局的时候,系统做了什么?

在AppCompatActivity中

@Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

可以看到AppCompatDelegate中

public abstract void setContentView(@LayoutRes int resId);

是一个抽象方法
接下来看这个getDelegate是什么

/**
     * @return The {@link AppCompatDelegate} being used by this Activity.
     */
    @NonNull
    public AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, this);
        }
        return mDelegate;
    }

AppCompatDelegate是一个类似工厂类的抽象类,会根据sdk版本create不同的子类

/**
     * Create a {@link android.support.v7.app.AppCompatDelegate} to use with {@code dialog}.
     *
     * @param callback An optional callback for AppCompat specific events
     */
    public static AppCompatDelegate create(Dialog dialog, AppCompatCallback callback) {
        return create(dialog.getContext(), dialog.getWindow(), callback);
    }

    private static AppCompatDelegate create(Context context, Window window,
            AppCompatCallback callback) {
        final int sdk = Build.VERSION.SDK_INT;
        if (BuildCompat.isAtLeastN()) {
            return new AppCompatDelegateImplN(context, window, callback);
        } else if (sdk >= 23) {
            return new AppCompatDelegateImplV23(context, window, callback);
        } else if (sdk >= 14) {
            return new AppCompatDelegateImplV14(context, window, callback);
        } else if (sdk >= 11) {
            return new AppCompatDelegateImplV11(context, window, callback);
        } else {
            return new AppCompatDelegateImplV9(context, window, callback);
        }
    }

我们就是要从这些实现类中找到setContentView方法
从源码中可以看到这些子类的继承关系

AppCompatDelegateImplN extends AppCompatDelegateImplV23
AppCompatDelegateImplV23 extends AppCompatDelegateImplV14
AppCompatDelegateImplV14 extends AppCompatDelegateImplV11
AppCompatDelegateImplV11 extends AppCompatDelegateImplV9
AppCompatDelegateImplV9 extends AppCompatDelegateImplBase
最终
AppCompatDelegateImplBase extends AppCompatDelegate

我们在AppCompatDelegateImplV9中找到setContentView方法

@Override
    public void setContentView(int resId) {
        //获取到mSubDecor,这是一个ViewGroup,在这个ViewGroup中有一个id为content的ViewGroup,最终我们设置的layout就是添加到这个id为content的ViewGroup中的
        ensureSubDecor();
        ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();
        LayoutInflater.from(mContext).inflate(resId, contentParent);
        mOriginalWindowCallback.onContentChanged();
    }

这里先简单看一下LayoutInflator inflate的源码,以后会具体分析,看完这个我们再分析mSubDecor的获取

LayoutInflater.from(mContext).inflate(resId, contentParent);

LayoutInflator中

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                    + Integer.toHexString(resource) + ")");
        }
        //从一个layout的id中解析出XmlResourceParser
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            final Context inflaterContext = mContext;
            //获取布局的参数
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;

            //解析这个xml布局
            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                //xml解析失败,没有找到start tag
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }

                final String name = parser.getName();

                ......
                

                //merge标签处理
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        ......
                        // 设置布局参数
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {                   
                            temp.setLayoutParams(params);
                        }
                    }
                    ......
                    // Inflate all children under temp against its context.
                    rInflateChildren(parser, temp, attrs, true);

                    ......
                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        //把view add到root中,inflate方法的作用其实就是把一个view添加到一个ViewGroup中
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            ......

            return result;
        }
    }

我们简单看下rInflate和rInflateChildren方法

rInflate

/**
     * Recursive method used to descend down the xml hierarchy and instantiate
     * views, instantiate their children, and then call onFinishInflate().
     * <p>
     * <strong>Note:</strong> Default visibility so the BridgeInflater can
     * override it.
     */
    void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;

        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();

            if (TAG_REQUEST_FOCUS.equals(name)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflateChildren(parser, view, attrs, true);
                //添加到布局中
                viewGroup.addView(view, params);
            }
        }

        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }
        //当布局inflate完成的时候,回调view的onFinishInflate方法,这个方法就是我们在自定义View时经常重写的那个onFinishInflate方法,
        //在这个方法中为什么获取不到view的宽高?因为只是布局inflate完成,还没有进行测量,onMeasure还没有开始
        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

rInflateChildren

/**
     * Recursive method used to inflate internal (non-root) children. This
     * method calls through to {@link #rInflate} using the parent context as
     * the inflation context.
     * <strong>Note:</strong> Default visibility so the BridgeInflater can
     * call it.
     */
    final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws XmlPullParserException, IOException {
        //最终调用的还是rInflate方法
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

看到这里我们知道了一些东西,setContentView方法就是将我们设置的layout解析成view之后add到了mSubDecor的一个id为android.R.id.content的ViewGroup中(contentParent)了,然后再次回到setContentView 方法中的ensureSubDecor方法中,mSubDecor是什么?如何获取的?

private void ensureSubDecor() {
        if (!mSubDecorInstalled) {
            mSubDecor = createSubDecor();  
            .......
        }
    }
private ViewGroup createSubDecor() {
  
        ......

        // Now let's make sure that the Window has installed its decor by retrieving it
        mWindow.getDecorView();

        ......

        // Now set the Window's content view with the decor
        mWindow.setContentView(subDecor);

        ......

        return subDecor;
    }

这里的Window指的是PhoneWindow

mWindow.getDecorView();

//如果mDecor不存在就创建,所以官方注释说
Now let's make sure that the Window has installed its decor by retrieving it
@Override
    public final View getDecorView() {
        if (mDecor == null || mForceDecorInstall) {
            installDecor();
        }
        return mDecor;
    }

installDecor这个方法,我们关注两个点,第一,它创建了DecorView,并返回,
第二,通过DecorView创建了mContentParent

private void installDecor() {
        mForceDecorInstall = false;
        
        if (mDecor == null) {
            //如果mDecor为null,就创建出来
            mDecor = generateDecor(-1);
            ......
        } else {
            //给DecorView设置Window
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {
            //如果mContentParent为null,就创建出来
            mContentParent = generateLayout(mDecor);
            ........
        }
    }
    //DecorView是被new出来的
    protected DecorView generateDecor(int featureId) {

        ......

        return new DecorView(context, featureId, this, getAttributes());
    }
    
    protected ViewGroup generateLayout(DecorView decor) {
        ......
        //The ID that the main layout in the XML layout file should have.这是一个系统层面的ViewGroup
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        ......
        return contentParent;
    }

源码new出来了一个DecorView,然后再根据具体情况选取一个系统的布局add到DecorView中,subDecor就是这个系统布局,这个布局会被添加到DecorView中,DecorView又是被添加到PhoneWindow上
mWindow.setContentView(subDecor);

@Override
    public void setContentView(View view) {
        setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        if (mContentParent == null) {
            //确保mContentParent不为null,这里基本上不存在为null的情况,因为在
            //mWindow.getDecorView();的时候如果为 null就会创建出来
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            ......
        } else {
            //把subDecor加入了mContentParent
            mContentParent.addView(view, params);
        }
        ......
    }

这样一个过程下来,基本上setContentView的作用有了基本的结论
这里借用一下一位博主的图片来说明手机屏幕的View层级关系


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

推荐阅读更多精彩内容

  • 人们喜欢关注别人的成功,却喜欢聚焦自己的失败。 01 我曾经失败至极,省城创业,赔个精光。出发前有人说:“那里”水...
    鹿雯立love阅读 753评论 0 0
  • 落笔長嘘短叹, 内心如浪涌、千层乱。 又把往昔寻遍, 未想旧忆当抛, 丝连藕断。 不求承诺兑现, 何许永无变。 花...
    龍之風阅读 234评论 7 14
  • 1、要买也要买在闹市区,兰大旁边,别去那些荒郊野外了。 2、要注意用周易来规划,否则就是不行。每年开年或者时候要注...
    智囊团阅读 170评论 0 0
  • 最近很多人说《欢乐颂2》追不下去了,各个网站打分也很低。但我还在断断续续地看,甚至常看得泪流满面。 我很乐于看到在...
    冯尘阅读 355评论 0 2
  • 把钱花在自己身上是一种方法。更重要的是把时间,把注意力放在自己身上。只有这样才会让成长的速度达到最大。 践行老师提...
    大人黄桃阅读 156评论 0 0