【Android源碼】Activity如何加載布局

我們都知道在Activity中通過setContentView(layoutId)來加載布局文件流妻,使我們的布局文件能夠顯示在手機(jī)上,那么系統(tǒng)是如何將我們的布局文件加載到界面上的呢?

setContentView

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

通過setContentView的源碼可以發(fā)現(xiàn)其實(shí)是調(diào)用了Window的setContentView方法尚蝌,而Window是一個抽象類遭庶,PhoneWindow是Window的實(shí)現(xiàn)類。

// PhoneWindow.java
@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();
   }
   mContentParentExplicitlySet = true;
}

代碼中首先通過installDecor()創(chuàng)建出DecorView蓖乘。
之后再通過mLayoutInflater.inflate(layoutResID, mContentParent)將我們的布局加載進(jìn)內(nèi)存锤悄。

DecorView

private void installDecor() {
   mForceDecorInstall = false;
   if (mDecor == null) {
    // 創(chuàng)建DecorView
       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) {
    // 將android.R.id.content解析出來
       mContentParent = generateLayout(mDecor);
  }
}

installDecor主要有2個作用:

  1. 創(chuàng)建DeorView

    protected DecorView generateDecor(int featureId) {
       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());
    }
    
  2. 將android.R.id.content解析出來

    protected ViewGroup generateLayout(DecorView decor) {
        // Inflate the window decor.
       int layoutResource;
       int features = getLocalFeatures();
       // 各種判斷加載系統(tǒng)布局
       if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
           layoutResource = R.layout.screen_swipe_dismiss;
       } else {
           layoutResource = R.layout.screen_simple;
       }
    
       mDecor.startChanging();
       // 將得到的布局文件加載到DecorView中
       mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
        // 獲取android.R.id.content
       ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
    }
    

    generateLayout的作用就是:

    1. 通過條件獲取到系統(tǒng)需要加載的布局文件,這里我們以最簡單的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>
      
    2. 將得到的布局文件加載到DecorView中:

      void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
      
         mDecorCaptionView = createDecorCaptionView(inflater);
         final View root = inflater.inflate(layoutResource, null);
         if (mDecorCaptionView != null) {
             if (mDecorCaptionView.getParent() == null) {
                 addView(mDecorCaptionView,
                         new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
             }
             mDecorCaptionView.addView(root,
                     new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
         } else {
      
             // Put it below the color views.
             addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
         }
         mContentRoot = (ViewGroup) root;
         initializeElevation();
      

    }
    ```

    1. 獲取android.R.id.content

      public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
      
      ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
      

    至此系統(tǒng)的布局就加載好了嘉抒,大概的結(jié)構(gòu)如下:

inflate加載我們的布局

當(dāng)系統(tǒng)的布局通過installDecor()加載完成之后零聚,就會通過mLayoutInflater.inflate(layoutResID, mContentParent)加載我們自己設(shè)置進(jìn)去的布局。

而inflate的源碼分析請參考:

  1. 【Android源碼】LayoutInflater 分析
  2. 【Android源碼】View的創(chuàng)建流程
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末些侍,一起剝皮案震驚了整個濱河市隶症,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌岗宣,老刑警劉巖蚂会,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異耗式,居然都是意外死亡胁住,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進(jìn)店門刊咳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來彪见,“玉大人,你說我怎么就攤上這事娱挨∮嘀福” “怎么了?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵让蕾,是天一觀的道長浪规。 經(jīng)常有香客問我,道長探孝,這世上最難降的妖魔是什么笋婿? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮顿颅,結(jié)果婚禮上缸濒,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好庇配,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布斩跌。 她就那樣靜靜地躺著,像睡著了一般捞慌。 火紅的嫁衣襯著肌膚如雪耀鸦。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天啸澡,我揣著相機(jī)與錄音袖订,去河邊找鬼。 笑死嗅虏,一個胖子當(dāng)著我的面吹牛洛姑,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播皮服,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼楞艾,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了龄广?” 一聲冷哼從身側(cè)響起硫眯,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蜀细,沒想到半個月后舟铜,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡奠衔,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年谆刨,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片归斤。...
    茶點(diǎn)故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡痊夭,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出脏里,到底是詐尸還是另有隱情她我,我是刑警寧澤,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布迫横,位于F島的核電站番舆,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏矾踱。R本人自食惡果不足惜恨狈,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望呛讲。 院中可真熱鬧禾怠,春花似錦返奉、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至弦讽,卻和暖如春污尉,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背坦袍。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工十厢, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留等太,地道東北人捂齐。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像缩抡,于是被迫代替她去往敵國和親奠宜。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,515評論 2 359

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