Activity中setContentView是怎么样把布局加载到Activity上的?

前言

关于Activity的setContentView()方法相信大家都熟悉,一般放到Activity的onCreate()回调方法中使用,但是setContentView()方法,是怎么把布局渲染到Activity上的呢?下面我们就带着这个问题,一起来剖析下setContentView的源码。

剖析

Activity中的setContentView:

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

在这里我们重点关注下getWindow().setContentView(layoutResID);首先getWindow(),相信大家都熟悉了。每个Activity都持有一个Window对象,而因为Window类是个抽象类,它的唯一的子类是PhoneWindow。我们可以追踪一下Activity中的getWindow()方法:

public Window getWindow() {
        return mWindow;
}

由上可以看出getWindow()方法,只是返回了Activity中的一个mWindow变量。那么这个mWindow变量又是在哪里给赋值的呢?

我们可以看下Activity类中attach方法,这个方法是final修饰的,不可以被重写:

@UnsupportedAppUsage
    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,
            Window window, ActivityConfigCallback activityConfigCallback, IBinder assistToken) {
        ...

        mWindow = new PhoneWindow(this, window, activityConfigCallback);
        mWindow.setWindowControllerCallback(this);
        mWindow.setCallback(this);
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);

        ...
    }

由此,我们看出getWindow()方法其实返回的就是一个PhoneWindow对象,那么也就说明了getWindow().setContentView(layoutResID);其实调用的是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);
        }
        
    ...
}

不难看出,这个setContentView方法其实是调用了:

mLayoutInflater.inflate(layoutResID, mContentParent);

这个layoutResID,是我们传进来的R.layout.main_activity;,那第二个参数,mContentParent是在哪里得到的呢?

我们看下上面的installDecor();方法:

这里主要关注两个方法:generateDecor和generateLayout。

generateDecor方法创建了一个DecorView的对象并返回这个对象:

protected DecorView generateDecor(int featureId) {
        ...
        return new DecorView(context, featureId, this, getAttributes());
}

generateLayout方法:

protected ViewGroup generateLayout(DecorView decor) {

    ...

    int layoutResource;
    int features = getLocalFeatures();
       
        if (...) {
            ...
        } else {
            // Embedded, so no decoration is needed.
            layoutResource = R.layout.screen_simple;
            // System.out.println("Simple!");
        }

        mDecor.startChanging();
        mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);

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

    return contentParent;
}

这里出现了一个布局:R.layout.screen_simple;,这个xml布局其实是这样的:

<?xml version="1.0" encoding="utf-8"?>
<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="?attr/windowContentOverlay"/>


</LinearLayout>

并且调用了DecorView的mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);方法,把这个布局填充到了DecorView上:

 之后,又通过findViewById获取到了id为ID_ANDROID_CONTENT的控件对象,即R.layout.screen_simple布局中的FrameLayout。并把FrameLayout对象返回,并赋值给mContentParent变量:

然后,把我们Activity中通过setContentView传进来的布局,填充到mContentParent上:

mLayoutInflater.inflate(layoutResID, mContentParent);

总结

经过上面的剖析,我们了解了Activity的setContentView是怎么把传进去的布局渲染到Activity上。下面附上一个Activity界面上的结构图:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值