从setContentView说开来

本文参考:
[1]工匠若水 Android应用setContentView与LayoutInflater加载解析机制源码分析
[2]鸿洋 Android 源码解析 之 setContentView

本文致力于弄清这几个问题:

1.setViewContent(R.layout.main_activity)。这个方法究竟是做什么的?

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

2.这个方法为什么普遍都在onCreate中执行?是否可以自由选择时机?

3.为什么 requestFeature() 要放在setContentView 之前执行?
http://stackoverflow.com/questions/4250149/requestfeature-must-be-called-before-adding-content>

为了理解方便,本文分析的源码版本对应的sdk版本是api 18。

一.setContentView官方介绍

看一下Android Developer Activity 的注解

An activity is a single, focused thing that the user can do. Almost all activities interact with the user, so the Activity class takes care of creating a window for you in which you can place your UI with setContentView(View).

从这里可以拿到两个比较重要的信息:
- activity会先为我们构造一个Window(又是一个接触比较少的概念)
- setContentView会将UI放置在Window中

二.追根溯源前的一点点废话

其实看源码是需要有一定的代码阅读量的。我觉得最重要的一点,一定要学会分析数据流。所谓数据流,就是看这个值是从哪一个类传过来的,又在哪里被使用或者赋给了别的变量。

这个道理其实非常浅显,我们使用Android Studio 时,查看变量的引用,红色的就是变量的赋值(数据的上游),绿色的就是变量的使用(数据的流向)。

我不喜欢在分析源码的过程中去说看到这个是从哪里赋值的。这非常消耗读者的注意力,有兴趣的读者是可以按照提供的信息去自己探索的。

其次,一定要画类图,不一定使用UML那一套,一定要让自己看懂,在阅读Android源码时,往往会有很多层的封装,如果搞不清楚,那么往往是读了半天,似懂非懂。

从setContentView说开来_第1张图片

三.跟随setContentView的脚步

我们探索的路径上这样编排,基本上是按照调用顺序

  1. Activity.setCotentView
  2. PhoneWindows.setContentView
  3. PhoneWindows.installDecor
  4. ActivityThread.handleResumeActivity

看完这几个流程,我们就可以清楚地知道到底我们的layout是如何显示在屏幕上的。

1. Activity.setCotentView

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

window 的赋值是在Activity.attach中(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,
            Window window) {
        attachBaseContext(context);

        mFragments.attachHost(null /*parent*/);

        mWindow = new PhoneWindow(this, window);
        mWindow.setWindowControllerCallback(this);
        mWindow.setCallback(this);
        mWindow.setOnWindowDismissedCallback(this);
        mWindow.getLayoutInflater().setPrivateFactory(this);
        if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
            mWindow.setSoftInputMode(info.softInputMode);
        }
        if (info.uiOptions != 0) {
            mWindow.setUiOptions(info.uiOptions);
        }
        mUiThread = Thread.currentThread();

注意到mWindow是新创建的。
同时,mWindows 还注册了几个callback为Activity。

从这里其实可以看到,Windows和Activity是不分家的,Activity持有Windows,Windows有一大堆回调最终是指向Activity的。而且Windows和Activity是一一对应的关系。这种情况下,其实我们已经可以把Windows看做是Activity的子集。

2 PhoneWindows.setContentView

顺着刚才getWindow().setContentView(layoutResID);继续往下看
PhoneWindows.setContentView做了以下工作:
1. 初始化mContentParent(一个ViewGroup,是用户自定义布局的直接父布局)

  1. inflate出用户自定义布局
  2. 通知Activity 回调onContentChanged
    @Override
    public void setContentView(int layoutResID) {
        if (mContentParent == null) {
            //初始化DecorView和其子布局mContentParent(也是用户自定义View的直接父布局)
            installDecor();
        } else {
            mContentParent.removeAllViews();
        }
       //真正的Inflater
        mLayoutInflater.inflate(layoutResID, mContentParent);
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            //实际上就是activity
            cb.onContentChanged();
        }
    }

3. PhoneWindows.installDecor

将目光转向2中的这个mContentParent,看起来就是在这个installDecor()中完成它的初始化。
继续深究会指向其中的一个其父布局—>DecorView(FrameLayout)

在这一步,我们主要可以看到:

Windows的各种属性,是如何反映在DecorView上。
installDecor的主要工作在PhoneWindow.generateLayout 中完成,其基本架构如下:

protected ViewGroup generateLayout(DecorView decor) {
        // Apply data from current theme.

        TypedArray a = getWindowStyle();


       ...//解析窗口的各种属性

        // Inflate the window decor.

        int layoutResource;

        ...//选取layoutResource

        mDecor.startChanging();

        View in = mLayoutInflater.inflate(layoutResource, null);
        decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));

        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);

        ...


        mDecor.finishChanging();

        return contentParent;
    }

这里有非常多的属性,处理也没有一致性可言。限于能力,这里不做讲解。需要的读者可以阅读qinjuning的《Andriod中Style/Theme原理以及Activity界面文件选取过程浅析》(http://blog.csdn.net/qinjuning/article/details/8829877) 2.1章之后的部分。

我们随意找到一个layoutResouce,其布局如下:
com.android.internal.R.layout.screen_action_bar;


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:fitsSystemWindows="true">
    <com.android.internal.widget.ActionBarContainer android:id="@+id/action_bar_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        style="?android:attr/actionBarStyle">
        <com.android.internal.widget.ActionBarView
            android:id="@+id/action_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            style="?android:attr/actionBarStyle" />
        <com.android.internal.widget.ActionBarContextView
            android:id="@+id/action_context_bar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"
            style="?android:attr/actionModeStyle" />
    com.android.internal.widget.ActionBarContainer>

    <FrameLayout android:id="@android:id/content"
        android:layout_width="match_parent" 
        android:layout_height="0dip"
        android:layout_weight="1"
        android:foregroundGravity="fill_horizontal|top"
        android:foreground="?android:attr/windowContentOverlay" />
    <com.android.internal.widget.ActionBarContainer android:id="@+id/split_action_bar"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  style="?android:attr/actionBarSplitStyle"
                  android:visibility="gone"
                  android:gravity="center"/>
LinearLayout>

所以,generateLayout的主要作用在于,初始化了decorView,完成了窗口中的主要布局,并且返回了mContentParent以添加用户自定义View。

4. ActivityThread.handleResumeActivity

让我们重新看看 2.PhoneWindow.setContentView中的代码:

    @Override
    public void setContentView(int layoutResID) {
        if (mContentParent == null) {
            //初始化DecorView和其子布局mContentParent(也是用户自定义View的直接父布局)
            installDecor();
        } else {
            mContentParent.removeAllViews();
        }
       //真正的Inflater
        mLayoutInflater.inflate(layoutResID, mContentParent);
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            //实际上就是activity
            cb.onContentChanged();
        }
    }

第二步虽然重要,但其实大部分复杂的整体布局等都放到了installDecor(generateLayout)来完成。
在完成了以上任务之后,我们发现,目前Windows拥有了decorView,并且已经将用户自定义View添加进来。但是,新创建的View此时还没有展示在屏幕上。真正添加进来还是要等到ActivityThread中的
handleResumeActivity,关键代码是:

 ActivityClientRecord r = performResumeActivity(token, clearHide);
 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);
                }
            } 

终于看到通过获取windowManage,终于将其添加到了屏幕之上。

四.小结

我们重新看看这4个部分,
Activity.setContentView 无疑只是api而已。实际操作是去交给了PhoneWindows去做的。PhoneWindow的大部分逻辑是依据Theme以及用户定义的各种FEATURE去构造界面(ActionBar等),完成了之后,通知Activity.onContentChanged。之后再添加到WindowManager上来显示。

开头提到的几个问题:
1.setContentView是做什么的?

一句话,为了将用户自定义布局添加进制定的布局中(DecorView的子布局)。

2.setContentView的调用时机?

任何地方,可以在onContentChanged中进行Activity View成员变量的初始化操作(findViewById等)。因为setContentView是同步操作,所以直接在setContentView之后findViewById也没什么问题。

3.为什么 requestFeature() 要放在setContentView 之前执行?

因为这些feature是在初始化DecorView的时候用到的。

这其中值得探索的部分还有1
1.Activity是怎样被创建的,和本文相关的onCreate以及handleActivityResume是怎样被调的。
2.第四步之后又发生了什么,WindowManager 的addView之后又发生了什么。

你可能感兴趣的:(Android开发,android应用,android,源码)