setContent方法源码解析

本文源码基于6.0分析。
首先看一下Activity中的setContentView。

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

我们可以看到实际上调用的是getWindow().setContentView(layoutResID),我们知道getWindow()获得的Window对象就是PhoneWindow对象,所以实际上调用的是PhoneWindow中的setContentView(layoutResID)。
PhoneWindow.java

    @Override
    public void setContentView(int layoutResID) {
        //如果mContentParent为null,说明窗口还没有加载内容,则初始化DecorView。
        if (mContentParent == null) {
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            //FEATURE_CONTENT_TRANSITIONS标志位,这个是标记当前内容加载有没有使用过度动画,也就是转场动画。
            //否则mContentParent不为null,说明已经加载过了,并且没有使用转场动画,那么remove所以view。
            mContentParent.removeAllViews();
        }
        //如果使用转场动画,则调用transitionTo方法
        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
            //否则将我们的资源文件通过LayoutInflater对象转换为View树,并且添加至mContentParent视图中。
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
    }

接下来我们详细分析以下setContentView方法中调用的方法。
先看一下installDecor()方法。

    private void installDecor() {
        if (mDecor == null) {
            //如果mDecor为null,调用generateDecor()创建
            mDecor = generateDecor();
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        }
        //mContentParent为 null说明DecorView并未加载到mContentParent中。
        if (mContentParent == null) {
            //调用generateLayout方法给mContentParent赋值
            mContentParent = generateLayout(mDecor);
            mDecor.makeOptionalFitsSystemWindows();

            final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
                    R.id.decor_content_parent);

            //设置TitleView(TextView),Backdroud等资源,设置有无转场动画以及转场动画的种类
            ......
    }
    protected DecorView generateDecor() {
        return new DecorView(getContext(), -1);
    }
protected ViewGroup generateLayout(DecorView decor) {
        TypedArray a = getWindowStyle();
        ......
        //设置style为Window_windowNoTitle或者Window_windowActionBar
        if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
            requestFeature(FEATURE_NO_TITLE);
        } else if (a.getBoolean(R.styleable.Window_windowActionBar, false)) {
            // Don't allow an action bar if there is no title.
            requestFeature(FEATURE_ACTION_BAR);
        }
        //省略一些style资源的判断
        ......
        //添加布局到DecorView,前面我们通过generateDecor() 创建DecorView,现在DecorView里面还是null的,下面通过设置的Feature来创建相应的布局。
        //举个例子,如果我在setContentView之前调用了requestWindowFeature(Window.FEATURE_NO_TITLE),这里则会通过getLocalFeatures来获取你设置的feature,进而加载对应的布局,
        //此时是加载没有标题栏的主题,这也就是为什么我们在代码中设置Theme或者requesetFeature()的时候必须在setContentView之前的原因.
        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();
        //将相应的布局解析成View并添加到decorView中。
        View in = mLayoutInflater.inflate(layoutResource, null);
        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        mContentRoot = (ViewGroup) in;

        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        ......

        mDecor.finishChanging();
        //generateLayout()的返回是contentParent,而它的获取则是ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        //DecorView是顶级View,它可以标示整个屏幕,其中包含状态栏,导航栏,内容区等等。这里的mContentParent指的是屏幕显示的内容区,而我们设置的activity_main.xml布局则是mContentParent里面的一个子元素。
        return contentParent;
    }

screen_simple.xml

<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>

我们再次回到PhoneWindow类的setContentVeiw()方法中,通过调用installDecor()方法,我们已经创建了DecorView,并获取到了mContentParent,接着就是将我们setContentView的内容添加到mContentParent中,也就是mLayoutInflater.inflate(layoutResID, mContentParent);

@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();
        }
    }

我们先看一下最后几句代码

       final Callback cb = getCallback();
          if (cb != null && !isDestroyed()) {
             cb.onContentChanged();
        }

这个CallBack是Window内部的一个接口,Window中实现了setCallback和getCallback方法。setCallback()方法是在Activity中被调用的。

final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor) {

        mWindow = new PhoneWindow(this);
}

而Activity本身也实现了Window.Callback接口,我们看一下Activity中实现的onContentChanged()方法。

public void onContentChanged() {
}

该方法是一个空方法,而当Activity的布局改动时,即setContentView()或者addContentView()方法执行完毕时就会调用该方法。我们日常开发时可以利用起来。
接下来我们分析一下LayoutInflater.inflat()方法,看是如何将我们自己的布局加载上去的。
到目前为止,通过setContentView方法,创建了DecorView和加载了我们自己的布局,但是View还是不可见的,因为我们只是加载了布局,并没有对View进行任何的测量、布局、绘制工作。
在View进行测量流程之前,还要进行一个步骤,那就是把DecorView添加至window中。
要说把DecorView添加到Window中,那我们就要从Activity的启动说起了,Activity启动的过程中必经的一步—ActivityThread类中的的handleLaunchActivity()方法。

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ......
        Activity a = performLaunchActivity(r, customIntent);

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

            ......
        } else {
            ......
        }
    }

我们来看一下performLaunchActivity(r, customIntent)。

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        ......
        Activity activity = null;
        try {
            java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
            activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
            }
        ......
        try {
            Application app = r.packageInfo.makeApplication(false, mInstrumentation);
            ......

            if (activity != null) {
                Context appContext = createBaseContextForActivity(r, activity);
                CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
                Configuration config = new Configuration(mCompatConfiguration);
                ......

                if (customIntent != null) {
                    activity.mIntent = customIntent;
                }
                r.lastNonConfigurationInstances = null;
                activity.mStartedActivity = false;
                int theme = r.activityInfo.getThemeResource();
                if (theme != 0) {
                    activity.setTheme(theme);
                }

                activity.mCalled = false;
                if (r.isPersistable()) {
                    mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);    
                } else {
                    mInstrumentation.callActivityOnCreate(activity, r.state);
                }
                ......
            }
            r.paused = true;

            mActivities.put(r.token, r);

        }

        return activity;
    }

调用了Instrumentation类的newActivity方法。Instrumentation类是一个全权负责Activity生命周期的类。

public Activity newActivity(Class<?> clazz, Context context, 
            IBinder token, Application application, Intent intent, ActivityInfo info, 
            CharSequence title, Activity parent, String id,
            Object lastNonConfigurationInstance) throws InstantiationException, 
            IllegalAccessException {
        Activity activity = (Activity)clazz.newInstance();
        ActivityThread aThread = null;
        activity.attach(context, aThread, this, token, 0, application, intent,
                info, title, parent, id,
                (Activity.NonConfigurationInstances)lastNonConfigurationInstance,
                new Configuration(), null, null);
        return activity;
    }

通过反射创建了一个新的Activity实例,在该方法中调用了Activity类中的attach()方法,回到performLaunchActivity方法中,接下来会调用Instrumentation类的callActivityOnCreate方法。

public void callActivityOnCreate(Activity activity, Bundle icicle) {
        prePerformCreate(activity);
        activity.performCreate(icicle);
        postPerformCreate(activity);
    }

调用了Activity中的performCreate方法。

final void performCreate(Bundle icicle) {
        onCreate(icicle);
        mActivityTransitionState.readState(icicle);
        performCreateCommon();
    }

调用了onCreate方法,我们知道onCreate方法是Activity的第一个生命周期方法,在这里我们调用了setContentView(),整个performLaunchActivity()函数就会返回一个已经执行完onCreat()和setContetnView()的activity对象,之前我们说setContentView()执行完之后,View此时还是不可见的,要等DecorView添加至window中,然后触发ViewRootImpl#performTraversals方法开始View的绘制,测量等工作后才会可见。
回到ActivityThread中handleLaunchActivity方法继续看,在执行完performLaunchActivity方法后会执行handleResumeActivity方法。

final void handleResumeActivity(IBinder token,
            boolean clearHide, boolean isForward, boolean reallyResume) {
        ......
        ActivityClientRecord r = performResumeActivity(token, clearHide);

        if (r != null) {
            final Activity a = r.activity;

            ......
            if (r.window == null && !a.mFinished && willBeVisible) {
                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 (a.mVisibleFromClient) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l);
                }

            } else if (!willBeVisible) {
                if (localLOGV) Slog.v(
                    TAG, "Launch " + r + " mStartedActivity set");
                r.hideForNow = true;
            }
            cleanUpPendingRemoveWindows(r);

            if (!r.activity.mFinished && willBeVisible
                    && r.activity.mDecor != null && !r.hideForNow) {
               ......
                WindowManager.LayoutParams l = r.window.getAttributes();
                if ((l.softInputMode
                        & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
                        != forwardBit) {
                    l.softInputMode = (l.softInputMode
                            & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
                            | forwardBit;
                    if (r.activity.mVisibleFromClient) {
                        ViewManager wm = a.getWindowManager();
                        View decor = r.window.getDecorView();
                        wm.updateViewLayout(decor, l);
                    }
                }
                r.activity.mVisibleFromServer = true;
                mNumVisibleActivities++;
                if (r.activity.mVisibleFromClient) {
                    r.activity.makeVisible();
                }
            }

            ......
        } else {
            try {
                ActivityManagerNative.getDefault()
                    .finishActivity(token, Activity.RESULT_CANCELED, null, false);
            } catch (RemoteException ex) {
            }
        }
    }

首先执行了performResumeActivity()方法

public final ActivityClientRecord performResumeActivity(IBinder token,
            boolean clearHide) {
        ActivityClientRecord r = mActivities.get(token);
        if (r != null && !r.activity.mFinished) {
            if (clearHide) {
                r.hideForNow = false;
                r.activity.mStartedActivity = false;
            }
            try {
                r.activity.onStateNotSaved();
                r.activity.mFragments.noteStateNotSaved();
                if (r.pendingIntents != null) {
                    deliverNewIntents(r, r.pendingIntents);
                    r.pendingIntents = null;
                }
                if (r.pendingResults != null) {
                    deliverResults(r, r.pendingResults);
                    r.pendingResults = null;
                }
                r.activity.performResume();
                ......
            } catch (Exception e) {
                ......
            }
        }
        return r;
    }

可看到执行了r.activity.performResume();即Activity中的performResume()方法。

final void performResume() {
        ......
        mInstrumentation.callActivityOnResume(this);
        ......

        onPostResume();
        if (!mCalled) {
            throw new SuperNotCalledException(
                "Activity " + mComponent.toShortString() +
                " did not call through to super.onPostResume()");
        }
    }

调用了Instrumentation类中的callActivityOnResume()方法.

public void callActivityOnResume(Activity activity) {
        activity.mResumed = true;
        activity.onResume();
        
       ......
    }

可以看到最终调用了Activity的生命周期方法onResume()。
继续看handleResumeActivity()方法中,performResumeActivity()方法执行完毕后,也就是执行到onResume()方法,此时内容仍然是不可见的,并且还没有执行View的测量、摆放、绘制等操作,因此此时获取View的宽高仍然是0。
handleResumeActivity()方法中。

    r.window = r.activity.getWindow();
    View decor = r.window.getDecorView();   
    decor.setVisibility(View.INVISIBLE);
    ViewManager wm = a.getWindowManager();

r.activity.getWindow()获得当前Activity的PhoneWindow对象.
View decor = r.window.getDecorView();获得当前phoneWindow内部类DecorView对象.
decor.setVisibility(View.INVISIBLE);刚获得这个DecorView的时候先设置为不可见.
ViewManager wm = a.getWindowManager();创建一个ViewManager对象.

public WindowManager getWindowManager() {
        return mWindowManager;
    }

mWindowManager唯一赋值的地方在Activity中的attach方法中。

final void attach(Context context, ActivityThread aThread,
            Instrumentation instr, IBinder token, int ident,
            Application application, Intent intent, ActivityInfo info,
            CharSequence title, Activity parent, String id,
            NonConfigurationInstances lastNonConfigurationInstances,
            Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
        ......
        mWindowManager = mWindow.getWindowManager();
    }

我们继续到Window中看一下getWindowManager()的实现。

public WindowManager getWindowManager() {
        return mWindowManager;
    }

Window类中mWindowManager唯一赋值的地方在setWindowManager方法中。

public void setWindowManager(WindowManager wm, IBinder appToken, String appName,
            boolean hardwareAccelerated) {
        ......
        mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);
    }

调用了WindowManagerImpl中的createLocalWindowManager()方法

public WindowManagerImpl createLocalWindowManager(Window parentWindow) {
        return new WindowManagerImpl(mDisplay, parentWindow);
    }

可以看到,最终实际上是new了一个WindowManagerImpl对象。
也就是说ViewManager wm = a.getWindowManager();返回的wm是一个WindowManagerImpl类的实例。
继续回到handleResumeActivity方法中。

 WindowManager.LayoutParams l = r.window.getAttributes();
 a.mDecor = decor;
 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
 l.softInputMode |= forwardBit;
 if (a.mVisibleFromClient) {
     a.mWindowAdded = true;
     wm.addView(decor, l);
 }

获取Window的LayoutParams属性,将mWindowAdded属性置为true,然后将DecorView添加到wm中,即添加到Window中,此时才是真正将View添加到Window中。
看一下addView方法的实现。

    @Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mDisplay, mParentWindow);
    }

可以看到实际上调用了WindowManagerGlobal的addView方法。

public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        ......

        final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
        if (parentWindow != null) {
            parentWindow.adjustLayoutParamsForSubWindow(wparams);
        } else {
            final Context context = view.getContext();
            if (context != null
                    && (context.getApplicationInfo().flags
                            & ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
                wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
            }
        }

        ViewRootImpl root;
        View panelParentView = null;

        synchronized (mLock) {
            ......

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

            view.setLayoutParams(wparams);

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

        try {
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
            synchronized (mLock) {
                final int index = findViewLocked(view, false);
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
            }
            throw e;
        }
    }

可以看到最终还是调用了ViewRootImpl的setView方法。

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
                mView = view;

                ......
                mAdded = true;
                int res; /* = WindowManagerImpl.ADD_OKAY; */
                requestLayout();
                if ((mWindowAttributes.inputFeatures
                        & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
                    mInputChannel = new InputChannel();
                }
                try {
                    mOrigWindowType = mWindowAttributes.type;
                    mAttachInfo.mRecomputeGlobalAttributes = true;
                    collectViewAttributes();
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mInputChannel);
                } catch (RemoteException e) {
                    mAdded = false;
                    ......
                } finally {
                    if (restore) {
                        attrs.restore();
                    }
                }
                ......
            }
        }
    }

传进来的view就是DecorView,首先将mAdded置为true,表明已经成功添加了DecorView,然后调用requestLayout()方法重绘界面。

    @Override
    public void requestLayout() {
        if (!mHandlingLayoutInLayoutRequest) {
            checkThread();
            mLayoutRequested = true;
            scheduleTraversals();
        }
    }

首先调用了checkThread()方法去检查是否在当前线程,这也是为什么我们在子线程中操作View会报异常的原因。接下来调用scheduleTraversals()方法。

void scheduleTraversals() {
        if (!mTraversalScheduled) {
            mTraversalScheduled = true;
            mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
            mChoreographer.postCallback(
                    Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
            if (!mUnbufferedInputDispatch) {
                scheduleConsumeBatchedInput();
            }
            notifyRendererOfFramePending();
            pokeDrawLockIfNeeded();
        }
    }

调用到了mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null),我们看一下mTraversalRunnable这个Runnable对象。

final class TraversalRunnable implements Runnable {
        @Override
        public void run() {
            doTraversal();
        }
    }

继续看doTraversal()方法的实现。

 void doTraversal() {
        if (mTraversalScheduled) {
            mTraversalScheduled = false;
            mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);

            performTraversals();

            if (mProfile) {
                Debug.stopMethodTracing();
                mProfile = false;
            }
        }
    }

里面有一个很重要的方法,performTraversals()它就是我们View真正开始测量、摆放、绘制的入口了。该方法中会依次调用performMeasure、performLayout、performDraw()操作,具体的View绘制流程我们单独拿一篇文章做讲解,这里不做深究。
好我们继续回到handleResumeActivity方法中,刚才是分析的WindowManagerImpl的addView方法,最终会执行到performTraversals()来执行View的绘制。
我们知道此时DecorView已经被添加到了Window中了,但是在添加之前DecorView被设置成不可见了,decor.setVisibility(View.INVISIBLE);
因此此时还是不可见状态,我们继续看handleResumeActivity方法,最后我们可以看到这样一段代码:

if (r.activity.mVisibleFromClient) {
      r.activity.makeVisible();
}

进入到Activity中看一下makeVisible()方法的实现。

   void makeVisible() {
        if (!mWindowAdded) {
            ViewManager wm = getWindowManager();
            wm.addView(mDecor, getWindow().getAttributes());
            mWindowAdded = true;
        }
        mDecor.setVisibility(View.VISIBLE);
    }

我们看到最终调用mDecor.setVisibility(View.VISIBLE)来将DecorView设置成可见,界面也就显示出来了。
从Activity的生命周期的角度来看,也就是onResume()执行完之后,DecorView才开始attach给WindowManager从而显示出来。
总结一下:
Activity在onCreate之前调用attach方法,在attach方法中会创建window对象。window对象创建时并没有创建Decor对象。用户在Activity中调用setContentView,然后调用window的setContentView,这时会检查DecorView是否存在,如果不存在则创建DecorView对象,然后把用户自己的View 添加到DecorView中。
至此,我们就分析完了setContentView方法的流程。
下一篇将分析View的绘制流程,将从performTraversals()方法开始分析。

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

推荐阅读更多精彩内容