Activity的setContentView()源碼分析

閱讀setContentView()源碼的疑問

首先讀源碼要帶著自己的疑問來讀源碼寞埠,setContentView()到底做了什么,為什么調(diào)用后就可以顯示出我們想要的布局頁面新翎?getWindow().requestFeature(Window.FEATURE_NO_TITLE);為什么要在setContentView()之前調(diào)用,下面我就就帶著這些疑問來一探究竟。

     /**
     * Set the activity content from a layout resource.  The resource will be
     * inflated, adding all top-level views to the activity.
     *
     * @param layoutResID Resource ID to be inflated.
     *
     * @see #setContentView(android.view.View)
     * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
     */
    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }

進(jìn)入到setContentView()额嘿,我們發(fā)現(xiàn)調(diào)用的是getWindow()的setContentView()方法,getWindow()其實就是一個Window劣挫,Window是一個抽象類册养,從注釋我們可以知道Window的唯一實現(xiàn)類是PhoneWindow。

/**
 * Abstract base class for a top-level window look and behavior policy.  An
 * instance of this class should be used as the top-level view added to the
 * window manager. It provides standard UI policies such as a background, title
 * area, default key processing, etc.
 *
 * <p>The only existing implementation of this abstract class is
 * android.view.PhoneWindow, which you should instantiate when needing a
 * Window.
 */
public abstract class Window 

也就是說Activity的setContentView()調(diào)用的是PhoneWindow的setContentView(),我們再看下PhoneWindow的setContentView().

 @Override
    public void setContentView(int layoutResID) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        if (mContentParent == null) {
            installDecor();  //1
        } 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);   //2
        }
      ...
    }

在這里會對mContentParent進(jìn)行判空压固,mContentParent是一個ViewGroup球拦,從名字和代碼②mLayoutInflater.inflate(layoutResID, mContentParent); 我們可以先猜測一下Activity要顯示的布局是不是就加載到mContentParent中呢?我們先留個疑問帐我,稍后分析inflate()坎炼。

    // This is the view in which the window contents are placed. It is either
    // mDecor itself, or a child of mDecor where the contents go.
    ViewGroup mContentParent;

注釋:這是放置窗口內(nèi)容的視圖。 它是mDecor本身拦键,或mDecor的一個孩子谣光。
當(dāng)mContentParent為null時,就會執(zhí)行代碼① installDecor();我們再進(jìn)入到 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);              //*********3**********
            ...
            }
        }
    }

當(dāng)我們新啟動一個Activity是mDecor 和 mContentParent 都是為空的抢肛,分別看下generateDecor()和generateLayout(mDecor)都做了什么。

創(chuàng)建generateDecor

protected DecorView generateDecor(int featureId) {
        // System process doesn't have application context and in that case we need to directly use
        // the context we have. Otherwise we want the application context, so we don't cling to the
        // activity.
        Context context;
        if (mUseDecorContext) {
            Context applicationContext = getContext().getApplicationContext();
            if (applicationContext == null) {
                context = getContext();
            } else {
                context = new DecorContext(applicationContext, getContext().getResources());
                if (mTheme != -1) {
                    context.setTheme(mTheme);
                }
            }
        } else {
            context = getContext();
        }
        return new DecorView(context, featureId, this, getAttributes());
    }

這里就是創(chuàng)建一個DecorView碳柱,DecorView又是什么呢捡絮?DecorView繼承于FrameLayout,在代碼3處將創(chuàng)建的這個DecorView作為參數(shù)傳到了generateLayout()中莲镣。

創(chuàng)建generateLayout

protected ViewGroup generateLayout(DecorView decor) {
        // Apply data from current theme.
        //獲得style屬性
        TypedArray a = getWindowStyle();
        ...
        ...
        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);
        }

        if (a.getBoolean(R.styleable.Window_windowActionBarOverlay, false)) {
            requestFeature(FEATURE_ACTION_BAR_OVERLAY);
        }

        if (a.getBoolean(R.styleable.Window_windowActionModeOverlay, false)) {
            requestFeature(FEATURE_ACTION_MODE_OVERLAY);
        }

        if (a.getBoolean(R.styleable.Window_windowSwipeToDismiss, false)) {
            requestFeature(FEATURE_SWIPE_TO_DISMISS);
        }
        ...
        // Inflate the window decor.
        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) {
                layoutResource = R.layout.screen_title_icons;
        } 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)福稳;    //*****4*****
        if ((features & (1 << FEATURE_INDETERMINATE_PROGRESS)) != 0) {
            ProgressBar progress = getCircularProgressBar(false);
            if (progress != null) {
                progress.setIndeterminate(true);
            }
        }

        if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
            registerSwipeCallbacks();
        }
        return contentParent;
    }

我們可以看到首先獲得style屬性,判斷是否有WindowNoTitle等等一些屬性瑞侮,然后調(diào)用一大堆requestFeature()和setFlags(),就是對Window一些狀態(tài)屬性的設(shè)置的圆,mContentParentExplicitlySet是一個標(biāo)記鼓拧,在調(diào)用setContentView()中就會設(shè)置為true,這就解開了文章開頭的疑問,為什么要在setContentView()之前設(shè)置requestFeature(Window.FEATURE_NO_TITLE);

     @Override
    public boolean requestFeature(int featureId) {
        if (mContentParentExplicitlySet) {
            throw new AndroidRuntimeException("requestFeature() must be called before adding content");
        }

上面其中還有一段代碼 int features = getLocalFeatures()越妈,來獲得對Window所設(shè)置的features 季俩,系統(tǒng)會根據(jù)features 來加載不同的XML文件,這個文件就是將要加載到window decor里面的,再次說明requestFeature()要在setContentView()之前設(shè)置梅掠,我們來看一下加載的其中一個XML文件R.layout.screen_simple酌住,

R.layout.screen_simple

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

這就是DecorView加載的布局,注意FrameLayout的id阎抒,通過代碼④找到這個id為ID_ANDROID_CONTENT的ViewGroup酪我,可以發(fā)現(xiàn)ID_ANDROID_CONTENT就是FrameLayout。

    /**
     * The ID that the main layout in the XML layout file should have.
     */
    public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;

最后又返回contentParent且叁,也就是說mContentParent 就是這個id為content的FrameLayout都哭。我們看下面的視圖


Activity加載UI-類圖關(guān)系和視圖結(jié)構(gòu).png

我們總結(jié)一下圖片,每一個Activity對應(yīng)一個Window,PhoneWindow是Window的子類逞带,DecorView是PhoneWindow的內(nèi)部類欺矫,加載Activity顯示的視圖,現(xiàn)在對窗口的視圖有了清晰的了解展氓。

LayoutInflater 把xml添加到Decorview分析

1.include 為什么不能xml資源布局的根節(jié)點汇陆?
2.merge 為什么作為xml資源布局的根節(jié)點?

我們來看下setContentView()中mLayoutInflater.inflate(layoutResID, mContentParent)的部分带饱,LayoutInflater的inflater(layoutResID毡代,mContentParent)方法

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                    + Integer.toHexString(resource) + ")");
        }

        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
    /**
     * Inflate a new view hierarchy from the specified XML node. Throws
     * {@link InflateException} if there is an error.
     * <p>
     * <em><strong>Important</strong></em>   For performance
     * reasons, view inflation relies heavily on pre-processing of XML files
     * that is done at build time. Therefore, it is not currently possible to
     * use LayoutInflater with an XmlPullParser over a plain XML file at runtime.
     * 
     * @param parser XML dom node containing the description of the view
     *        hierarchy.
     * @param root Optional view to be the parent of the generated hierarchy (if
     *        <em>attachToRoot</em> is true), or else simply an object that
     *        provides a set of LayoutParams values for root of the returned
     *        hierarchy (if <em>attachToRoot</em> is false.)
     * @param attachToRoot Whether the inflated hierarchy should be attached to
     *        the root parameter? If false, root is only used to create the
     *        correct subclass of LayoutParams for the root view in the XML.
     * @return The root View of the inflated hierarchy. If root was supplied and
     *         attachToRoot is true, this is root; otherwise it is the root of
     *         the inflated XML file.
     */
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);    //獲得的是Activity顯示布局的屬性
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;                                       //將DecorView布局中的FrameLayout賦值給result 
             ...
             // Look for the root node.                         //找到根節(jié)點
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                     // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    if (root != null) {
                        // Create layout params that match root, if supplied   //創(chuàng)建與root匹配的布局參數(shù)(如果提供)
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }
                    // Inflate all children under temp against its context.          //填充temp下面的子View
                    rInflateChildren(parser, temp, attrs, true);      
                    ...
                }
                ...
            return result;
        }
    }

上面三段代碼依次調(diào)用,如果是meger標(biāo)簽時調(diào)用 rInflate(parser, root, inflaterContext, attrs, false);如果不是meger標(biāo)簽時會調(diào)用View temp = createViewFromTag(root, name, inflaterContext, attrs); 上面有一句注釋// Temp is the root view that was found in the xml勺疼,意思是:Temp是在xml中找到的根視圖教寂,也就是我們Activity顯示布局的根視圖,然后調(diào)用root.generateLayoutParams(attrs);來解析根布局的參數(shù)并進(jìn)行設(shè)置执庐, 下面我們看下rInflateChildren(parser, temp, attrs, true)

    /**
     * Recursive method used to inflate internal (non-root) children. This
     * method calls through to {@link #rInflate} using the parent context as
     * the inflation context.
     * <strong>Note:</strong> Default visibility so the BridgeInflater can
     * call it.
     */
    final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws XmlPullParserException, IOException {
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

我們發(fā)現(xiàn)最后都是調(diào)用rInflate()只是最后一個參數(shù)finishInflate不同酪耕,meger傳false,反之轨淌。

    /**
     * Recursive method used to descend down the xml hierarchy and instantiate
     * views, instantiate their children, and then call onFinishInflate().
     * <p>
     * <strong>Note:</strong> Default visibility so the BridgeInflater can
     * override it.
     */
    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("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
![LayoutInflater.png](http://upload-images.jianshu.io/upload_images/4029647-7d295d44aaf5b9aa.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
                throw new InflateException("<merge /> 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();
        }
    }

我們發(fā)現(xiàn)是一個while循環(huán)迂烁,也就是通過遍歷去解析的,看下解析過程會判斷節(jié)點的名稱递鹉,其中判斷到TAG_INCLUDE和TAG_MERGE標(biāo)簽時我們會看到拋出兩個異常盟步,這就解釋了開始提出的兩個問題。最后else還是重復(fù)了rInflateChildren(),然后添加到viewGroup里面躏结,這個過程用下面圖片說明一下解析XML 的大致過程却盘。

LayoutInflater.png

現(xiàn)在我們用AS開發(fā)默認(rèn)都是繼承AppCompatActivity,那么AppCompatActivity的setContentView()也是這樣呢!黄橘!答案肯定不是的兆览,我們下篇分析!
(第一篇源碼分析文章塞关,希望讀者給出建議L健)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市帆赢,隨后出現(xiàn)的幾起案子驶睦,更是在濱河造成了極大的恐慌,老刑警劉巖匿醒,帶你破解...
    沈念sama閱讀 206,968評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異缠导,居然都是意外死亡廉羔,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,601評論 2 382
  • 文/潘曉璐 我一進(jìn)店門僻造,熙熙樓的掌柜王于貴愁眉苦臉地迎上來憋他,“玉大人,你說我怎么就攤上這事髓削≈竦玻” “怎么了?”我有些...
    開封第一講書人閱讀 153,220評論 0 344
  • 文/不壞的土叔 我叫張陵立膛,是天一觀的道長揪罕。 經(jīng)常有香客問我,道長宝泵,這世上最難降的妖魔是什么好啰? 我笑而不...
    開封第一講書人閱讀 55,416評論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮儿奶,結(jié)果婚禮上框往,老公的妹妹穿的比我還像新娘。我一直安慰自己闯捎,他們只是感情好椰弊,可當(dāng)我...
    茶點故事閱讀 64,425評論 5 374
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著瓤鼻,像睡著了一般秉版。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上茬祷,一...
    開封第一講書人閱讀 49,144評論 1 285
  • 那天沐飘,我揣著相機(jī)與錄音,去河邊找鬼。 笑死耐朴,一個胖子當(dāng)著我的面吹牛借卧,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播筛峭,決...
    沈念sama閱讀 38,432評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼铐刘,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了影晓?” 一聲冷哼從身側(cè)響起镰吵,我...
    開封第一講書人閱讀 37,088評論 0 261
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎挂签,沒想到半個月后疤祭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 43,586評論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡饵婆,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,028評論 2 325
  • 正文 我和宋清朗相戀三年勺馆,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片侨核。...
    茶點故事閱讀 38,137評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡草穆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出搓译,到底是詐尸還是另有隱情悲柱,我是刑警寧澤,帶...
    沈念sama閱讀 33,783評論 4 324
  • 正文 年R本政府宣布些己,位于F島的核電站豌鸡,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏段标。R本人自食惡果不足惜直颅,卻給世界環(huán)境...
    茶點故事閱讀 39,343評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望怀樟。 院中可真熱鬧功偿,春花似錦、人聲如沸往堡。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,333評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽虑灰。三九已至吨瞎,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間穆咐,已是汗流浹背颤诀。 一陣腳步聲響...
    開封第一講書人閱讀 31,559評論 1 262
  • 我被黑心中介騙來泰國打工字旭, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人崖叫。 一個月前我還...
    沈念sama閱讀 45,595評論 2 355
  • 正文 我出身青樓遗淳,卻偏偏與公主長得像,于是被迫代替她去往敵國和親心傀。 傳聞我的和親對象是個殘疾皇子屈暗,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 42,901評論 2 345

推薦閱讀更多精彩內(nèi)容