setContentView都干了些什么

简单的梳理一下setContentView()方法都干了什么。启动Activity之后,我们写的布局文件怎么就展示在了该Activity的页面之上。我们知道的window,windowmanager,decorview,viewrootImpl它们具体的职责是什么,并且它们之间又存在着什么关系。带着这些问题,通过阅读源码大致的捋一下思路,对Android布局的绘制过程有一个大概的轮廓框架。
先进入setContentView方法会看到,会来到Activity的setContentView方法中


   public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

看到调用到了getWindow()的setContentView方法,这个window类是一个抽象类,它有一个唯一的实现类,就是PhoneWindow。所以直接查看PhoneWindow的setContentView方法。

    @Override
    public void setContentView(int layoutResID) {
        if (mContentParent == null) {
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

mContentParent此时为空,会进入到installDecor()方法中。

private void installDecor() {
        mForceDecorInstall = false;
        if (mDecor == null) {
            mDecor = generateDecor(-1);
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        } else {
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {
            mContentParent = generateLayout(mDecor);
        ......
        ......
    }

首先mDecor为null,进入if块中的generateDecor()方法,为mDeocr赋值。当mDecor不为null时,就直接调用mDecor.setWindow(this);方法,将该phonewindow对象与该decorview相关连,decorview中有成员变量mWindow来指向所关联的phonewindow对象。在decorview的构造函数中也为mWindow赋值了。
此方法new了一个DecorView对象return了回来。接着调用generateLayout方法为mContentParent变量赋值。此方法就是设置DecorView的具体细节,

        int layoutResource;
        int features = getLocalFeatures();
        if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
            layoutResource = R.layout.screen_swipe_dismiss;
        } else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogTitleIconsDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else {
                layoutResource = R.layout.screen_title_icons;
            }
            removeFeature(FEATURE_ACTION_BAR);
        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
                && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
            layoutResource = R.layout.screen_progress;
        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogCustomTitleDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else {
                layoutResource = R.layout.screen_custom_title;
            }
            removeFeature(FEATURE_ACTION_BAR);
        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogTitleDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
                layoutResource = a.getResourceId(
                        R.styleable.Window_windowActionBarFullscreenDecorLayout,
                        R.layout.screen_action_bar);
            } else {
                layoutResource = R.layout.screen_title;
            }
        } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
            layoutResource = R.layout.screen_simple_overlay_action_mode;
        } else {
            layoutResource = R.layout.screen_simple;
        }

        mDecor.startChanging();
        mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);

以上代码的第二行通过getLocalFeatures()方法获取我们设置想要的样式,这也是为什么调用requestWindowFeature()方法要在setContentView()之前调用的原因,如果在之后调用,就获取不到我们想要设置的值,也就不会得到我们想要的效果。方法中一大段if的判断就是根据不同的feature来选择要在decorview下添加什么样的布局样式。如果什么都没有设置,会默认选择R.layout.screen_simple这个布局,然后会进入mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);这个方法中

void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
        mDecorCaptionView = createDecorCaptionView(inflater);
        final View root = inflater.inflate(layoutResource, null);
        if (mDecorCaptionView != null) {
            if (mDecorCaptionView.getParent() == null) {
                addView(mDecorCaptionView,
                        new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
            }
            mDecorCaptionView.addView(root,
                    new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
        } else {
            addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        }
        mContentRoot = (ViewGroup) root;
        initializeElevation();
    }

此段代码可以很清晰的看出是将layoutResource的布局inflater为一个view对象,并添加到了decorview下,并将decorview中的mContentRoot变量设置为了这个view对象。返回上一段代码,findViewById调用的就是Decorview的findviewById,而ID_ANDROID_CONTENT 的值为com.android.internal.R.id.content,看下R.layout.screen_simple布局到底是什么样子


    
    

可以很明显的看出,这个findviewById返回的这个ViewGroup就是此布局中的FrameLayout。
接着回到PhoneWindow的setContentView方法中执行mLayoutInflater.inflate(layoutResID, mContentParent);此方法会调用下面方法,resource为我们在activity中setContentView()中传入的布局ID,root为phonewindow的mContentParent,也就是DecorView中为id为content的framelayout

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

首先获取XmlResourceParser布局解析器,调用inflate(parser, root, attachToRoot); parser为解析器,root为mContentParent,attachToRoot为true.

public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;
            try {
                final String name = parser.getName();

                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException(" can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }
                    rInflateChildren(parser, temp, attrs, true);

                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }
            } 
            return result;
        }
    }

AttributeSet attrs = Xml.asAttributeSet(parser);解析布局封装到attrs中。View result = root;定义一个名为result的view指向mContentParent,这个result最终会被此方法当做返回值返回。然后获取到根节点的name,进入if判断,如果根节点是marge标签,而且如果mContentParent为空,或者attachToRoot为false,会抛出异常。接着会调用rInflate方法,此方法会在下面描述。如果跟布局不是marge标签,会进入else,一般情况下,都会走这里的代码。首先调用createViewFromTag方法返回一个跟布局标签的实例化对象temp。接着判断root如果不为空,调用root.generateLayoutParams方法返回该ViewGroup在xml布局中对应的LayoutParams。在此情景中,会返回给我们Framelayout.LayoutParams类型的layoutparams,此时判断attachToRoot为false,会走temp.setLayoutParams(params);但是此时attachToRoot为true,所以不会走此方法。来到了最重要的一句代码rInflateChildren(parser, temp, attrs, true);进入此方法就是调用的上面没展开的rInflate方法。

void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

        final int depth = parser.getDepth();
        int type;

        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)) {
                parseRequestFocus(parser, parent);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException(" cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException(" 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 (finishInflate) {
            parent.onFinishInflate();
        }
    }

此方法获取到布局的深度之后,while循环里开始执行以下逻辑:获取跟布局,进入if判断,如果不是requestFocus、tag、include、merge标签,就会进入else,此时的情景也是进去else,继续分析else的代码,跟上一个方法很类似,也是根据标签名创建对象,然后获取layoutparams,将此view添加到他的parent中,重复调用rInflateChildren方法。这个深度遍历过程结束后,DecorView中的framelayout已经被添加上了我们需要添加的布局。但是这仅仅是devorview有了视图,它又是怎样展示到了我们的activity上的呢?它们之间怎么关联在一起的呢?那就去activity的启动过程寻找看看了。

布局与Activity的关联

来到ActivityThread类中handleLaunchActivity方法中,Activity a =performLaunchActivity(r, customIntent);进入performLaunchActivity方法通过反射创建了该Activity实例,之后调用了该实例的attach方法,此方法中执行了一些与window有关的代码

        mWindow = new PhoneWindow(this, window);
        mWindow.setWindowControllerCallback(this);
        mWindow.setCallback(this);

该Activity对象实例化了一个PhoneWindow的成员变量,并设置了该windos对象的callback就是此Activity。然后执行了此代码,调用了activity的onCreate函数,mInstrumentation.callActivityOnCreate(activity, r.state);而onCreate中调用了我们熟悉的setContentView(R.layout.activity_main);完成了我们上面DecorView初始化,并把布局添加到DecorView中的framelayout中。

回到handleLaunchActivity方法中,初始化完Activity

if (a != null) {
            r.createdConfig = new Configuration(mConfiguration);
            reportSizeConfigurations(r);
            Bundle oldState = r.state;
            handleResumeActivity(r.token, false, r.isForward,
                    !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
}

此时a!=null成立,进入if执行了handleResumeActivity方法,重点看此方法中的这一段代码

                r.window = r.activity.getWindow();
                View decor = r.window.getDecorView();
                decor.setVisibility(View.INVISIBLE);
                ViewManager wm = a.getWindowManager();
                WindowManager.LayoutParams l = r.window.getAttributes();
                a.mDecor = decor;
                l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
                l.softInputMode |= forwardBit;
                if (r.mPreserveWindow) {
                    a.mWindowAdded = true;
                    r.mPreserveWindow = false;
                    ViewRootImpl impl = decor.getViewRootImpl();
                    if (impl != null) {
                        impl.notifyChildRebuilt();
                    }
                }
                if (a.mVisibleFromClient && !a.mWindowAdded) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l);
                }

主要看此段代码的最后一行,获取到Activity的windowmanger对象,执行wm.addView(decor, l);WindowManager是个接口,他的实现类是WindowManagerImpl,所以看它的addView方法,他的addView方法又调用了WindowManagerGlobal的addView。所以,直接查看WindowManagerGlobal的addView方法

 public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
          //......
          ViewRootImpl root;
          View panelParentView = null;
          //......  

            root = new ViewRootImpl(view.getContext(), display);

            view.setLayoutParams(wparams);

            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
        }

        // do this last because it fires off messages to start doing things
        try {
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
            // BadTokenException or InvalidDisplayException, clean up.
            synchronized (mLock) {
                final int index = findViewLocked(view, false);
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
            }
            throw e;
        }
    }

创建了一个ViewRootImpl类的实例,把decorview, viewRootImpl, wparams添加到相应的集合中,接着执行了root.setView方法,此方法重点有三部分代码

  1. requestLayout();:会执行scheduleTraversals方法,此方法又会执行一个TraversalRunnable的runnable对象,此对象run方法的实现是一个doTraversal();方法,它又会执行performTraversals();而此方法会依次执行performMeasure、performLayout、performDraw来进行绘制。
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mInputChannel);

通过跨进程方式通知WindowManagerService来添加此window.

  1. view.assignParent(this);将此ViewRootImpl的实例设置为该decorview的mParent。所以每个view调用requestLayout()方法进行重绘的时候,都会调用到父类的requestLayout,会一直调用到ViewRootImpl的requestLayout,而去执行scheduleTraversals()方法进行重绘。

总结

可以看到,

  • Windowmanager是单例的,它对所有的Window进行管理的类。它内部管理着ViewRootImpl,View,WindowManager.LayoutParams
  • window是描述窗口的抽象类,它是一个抽象的概念,没有具体的体现。所有的视图都依附它而存在。他的实现类PhoneWindow提供了操作窗口的实现。它包含一个decorview实例。
  • Decorview是所有布局的根view,它承载着对我们要显示布局的修饰。
  • ViewRootImpl是视图树的顶级view,是绘制的起点。它是window与view之间的桥梁

你可能感兴趣的:(setContentView都干了些什么)