从setContentVIew说开来

ffffff本文参考:
[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. 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,是用户自定义布局的直接父布局)

  2. inflate出用户自定义布局

  3. 通知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;

<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2010 The Android Open Source Project

     Licensed under the Apache License, Version 2.0 (the "License");
     you may not use this file except in compliance with the License.
     You may obtain a copy of the License at
  
          http://www.apache.org/licenses/LICENSE-2.0
  
     Unless required by applicable law or agreed to in writing, software
     distributed under the License is distributed on an "AS IS" BASIS,
     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     See the License for the specific language governing permissions and
     limitations under the License.
-->

<!--
This is an optimized layout for a screen with the Action Bar enabled.
-->

<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将成为用户自定义布局的父布局-->
    <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之后又发生了什么。

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

推荐阅读更多精彩内容