UI繪制流程及原理

一丶View是如何被添加到屏幕窗口上的

將大象裝進(jìn)冰箱需要三步衙猪,創(chuàng)建自定義View也是分為三部曲旱眯。

  • 1 創(chuàng)建頂層的布局容器DecorView
  • 2 在頂層布局中加載基礎(chǔ)布局的ViewGroup
  • 3 將ContentView添加到基礎(chǔ)布局的FrameLayout中

源碼分析,我們這里以Activity為例寻咒。
一般開(kāi)發(fā)中仁锯,我們給Activity設(shè)置布局的入口是setContentView()方法锣杂,進(jìn)入setContentView()方法匙姜。

一·找到setContentView的實(shí)現(xiàn)

/**
     * 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();
    }

這里面我們可以看到畅厢,實(shí)際調(diào)用的是getWindow()的setContenView方法,再來(lái)看看getWindow()方法氮昧,

 /**
     * Retrieve the current {@link android.view.Window} for the activity.
     * This can be used to directly access parts of the Window API that
     * are not available through Activity/Screen.
     *
     * @return Window The current window, or null if the activity is not
     *         visual.
     */
    public Window getWindow() {
        return mWindow;
    }

返回的是一個(gè)Window對(duì)象框杜。

/**
 * 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 {

這里Window是一個(gè)抽象類(lèi),從注釋中我們可以看出袖肥,PhoneWindow是Window的唯一實(shí)例咪辱。進(jìn)入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);
        }
        ...
    }

這個(gè)方法里面的主要做了兩件事情 installDecor()椎组,mLayoutInflater.inflate(layoutResID, mContentParent)(去解析當(dāng)前出傳入的 布局資源Id)油狂,接下來(lái),我們主要去看下 installDecor()方法,是如何加載一個(gè)DecorView 专筷。

二.了解installDecor()的加載過(guò)程

...
// This is the top-level view of the window, containing the window decor.
    private DecorView mDecor;
...
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);
            // Set up decor part of UI to ignore fitsSystemWindows if appropriate.
            mDecor.makeOptionalFitsSystemWindows();
          ...
                }
            }
        }
    }

通過(guò)installDecor()源碼的閱讀夹供,主要是做了兩件事。

  • 1.generateDecor() 創(chuàng)建一個(gè)DecorView仁堪;
  • 2.generateLayout() 將layoutResources(基礎(chǔ)布局)加載到DecorView。

下面來(lái)看一下詳細(xì)過(guò)程:

1.通過(guò)generateDecor方法獲取DecorView(頂層布局)
protected DecorView generateDecor(int featureId) {
        ...
        return new DecorView(context, featureId, this, getAttributes()); 
}

再看下DecorView的具體實(shí)現(xiàn)填渠。

public class DecorView extends FrameLayout implements RootViewSurfaceTaker, WindowCallbacks {

可以看到是DecorView 繼承FrameLayout的容器弦聂,這就說(shuō)明generateDecor()是獲取一個(gè)布局容器。

2.generateLayout()方法是將layoutResource(基礎(chǔ)布局)添加到DecorView
protected ViewGroup generateLayout(DecorView decor) {
         // Apply data from current theme. 設(shè)置系統(tǒng)主題的不同樣式和特性
         TypedArray a = getWindowStyle();
        ...
         if (mIsFloating) {
        ...
          setFlags(FLAG_LAYOUT_IN_SCREEN|FLAG_LAYOUT_INSET_DECOR, flagsToUpdate);
         }
         ...
            if (a.getBoolean(R.styleable.Window_windowNoTitle, false)) {
        ...
            requestFeature(FEATURE_NO_TITLE);
       }
        ...
       // Inflate the window decor. 解析decor
       int layoutResource;     //定義布局的資源變量
        int features = getLocalFeatures();
       ...
      if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
        layoutResource = R.layout.screen_simple_overlay_action_mode;
      } else {
      // Embedded, so no decoration is needed.
        layoutResource = R.layout.screen_simple;
      }
      ...
      mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
      ...
      ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
      if (contentParent == null) {
        throw new RuntimeException("Window couldn't find content container view");
      }
      ...
      return contentParent;
    } 
1.通過(guò)requestFeature()和setFlags()等方法設(shè)置系統(tǒng)主題的不同樣式和特性氛什。
2.解析窗口View
  • 1 . 根據(jù)具體的fetures的不同獲取到系統(tǒng)相應(yīng)的 layoutResources莺葫。
  • 2 . 獲取完layoutResource 后,通過(guò)mDecor.onResourcesLoaded()方法去解析這個(gè) layoutResources 枪眉。將解析獲得的view加載到DecorView上捺檬。
3 . 根據(jù)layoutResources (R.layout.screen_simple)上的布局ID:ID_ANDROID_CONTENT 獲取到相應(yīng)的 contentParent(實(shí)際上是一個(gè)R.layout.screen_simple 上的一個(gè)FrameLayout布局)并返回。
步驟一:

1.這里對(duì)不同feature和flags就不做深究了贸铜。

步驟二:

1 . 先通過(guò)fetures獲取相應(yīng)的 layoutResources這里我們假定根據(jù)某些特性條件下獲取到的是 layoutResource = R.layout.screen_simple;
2 . 執(zhí)行onResourcesLoaded()方法堡纬,解析 layoutResources,加載到 DecorView上

先查看源碼 onResourcesLoaded()源碼

 void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
       ...
        final View root = inflater.inflate(layoutResource, null);
       ...
            // Put it below the color views.
            addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        }
        ...
    }

在onResourcesLoaded 方法中蒿秦,他通過(guò)解析 layoutResource 創(chuàng)建了一個(gè)root對(duì)象烤镐。 該root對(duì)象例如為: R.layout.screen_simple(系統(tǒng)的xml)。通過(guò)addView方法將 root 對(duì)象加載到DecorView上棍鳖。

步驟三:

在onResourcesLoaded方法執(zhí)行完畢后炮叶,回到 generateLayout()方法中接下來(lái)我們會(huì)獲取到ViewGroup的對(duì)象 contentParent。那么這個(gè)contentParent是什么渡处?

ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        if (contentParent == null) {
            throw new RuntimeException("Window couldn't find content container view");
        }

首先通過(guò)查看ID_ANDROID_CONTENT 的注釋?zhuān)?我們可以看到這是系統(tǒng)主布局(我們這里假定獲取的是R.layout.screen_simple)一定所具有的ID 镜悉。com.android.internal.R.id.content。

 /**
     * 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;

我們查看screen_simple.xml医瘫,發(fā)現(xiàn)獲取到這個(gè)contentParent ,實(shí)際上是 screen_simple.xml 上的FrameLayout 侣肄。

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

獲取contentParent 并返回后,generateLayout()方法也就執(zhí)行完畢醇份。我們回到installDecor()方法中茫孔。
就此installDecor()的主要方法執(zhí)行完畢。 以上我們可以理解是在這個(gè)過(guò)程是獲取到DecorView被芳,然后將根據(jù)不同特性獲取到的系統(tǒng)的layoutResources加載到DecorView上缰贝。最后我們?cè)俑鶕?jù)ID_ANDROID_CONTENT 從layoutResources獲取到contentParent 。它實(shí)際上是一個(gè)FrameLayout畔濒。

三.加載setContentView中設(shè)置的布局

1.將setContentView中設(shè)置的布局加載到contentParent上
@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);
        }
        ...
    }

最后通過(guò):
mLayoutInflater.inflate(layoutResID, mContentParent);
將在activity上設(shè)置的布局 layoutResID 加載到 contentParent上 也就是 FrameLayout上剩晴。至此,我們的整個(gè)View就加載并顯示到屏幕上了。


image.png

總結(jié):

view是如何被添加到屏幕窗口上的赞弥?
1.首先系統(tǒng)會(huì)創(chuàng)建一個(gè)頂層布局容器DecorView毅整。DecorView 是一個(gè)ViewGroup容器, 繼承FrameLayout绽左,是PhoneWindow對(duì)象持有的一個(gè)實(shí)例悼嫉,他是所有應(yīng)用程序的頂層View,在系統(tǒng)內(nèi)部進(jìn)行初始化拼窥。當(dāng)DecorView 初始化完成后戏蔑,系統(tǒng)會(huì)根據(jù)應(yīng)用程序的頂層特性會(huì)加載一個(gè)基礎(chǔ)容器,例如no_actionBar等鲁纠,不同的主題加載的基礎(chǔ)容器也不一樣总棵,但是無(wú)論什么樣的的基礎(chǔ)容器一定會(huì)有一個(gè) android.R.di.content 的FrameLayout。開(kāi)發(fā)者通過(guò)setContView設(shè)置的xml 改含,通過(guò)解析后就加載到了這個(gè)FrameLayout中情龄。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市捍壤,隨后出現(xiàn)的幾起案子骤视,更是在濱河造成了極大的恐慌,老刑警劉巖鹃觉,帶你破解...
    沈念sama閱讀 216,919評(píng)論 6 502
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件尚胞,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡帜慢,警方通過(guò)查閱死者的電腦和手機(jī)笼裳,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,567評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)粱玲,“玉大人躬柬,你說(shuō)我怎么就攤上這事〕榧酰” “怎么了允青?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,316評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)卵沉。 經(jīng)常有香客問(wèn)我颠锉,道長(zhǎng),這世上最難降的妖魔是什么史汗? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,294評(píng)論 1 292
  • 正文 為了忘掉前任琼掠,我火速辦了婚禮,結(jié)果婚禮上停撞,老公的妹妹穿的比我還像新娘瓷蛙。我一直安慰自己悼瓮,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,318評(píng)論 6 390
  • 文/花漫 我一把揭開(kāi)白布艰猬。 她就那樣靜靜地躺著横堡,像睡著了一般。 火紅的嫁衣襯著肌膚如雪冠桃。 梳的紋絲不亂的頭發(fā)上命贴,一...
    開(kāi)封第一講書(shū)人閱讀 51,245評(píng)論 1 299
  • 那天,我揣著相機(jī)與錄音食听,去河邊找鬼胸蛛。 笑死,一個(gè)胖子當(dāng)著我的面吹牛碳蛋,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播省咨,決...
    沈念sama閱讀 40,120評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼肃弟,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了零蓉?” 一聲冷哼從身側(cè)響起笤受,我...
    開(kāi)封第一講書(shū)人閱讀 38,964評(píng)論 0 275
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎敌蜂,沒(méi)想到半個(gè)月后箩兽,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,376評(píng)論 1 313
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡章喉,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,592評(píng)論 2 333
  • 正文 我和宋清朗相戀三年汗贫,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片秸脱。...
    茶點(diǎn)故事閱讀 39,764評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡落包,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出摊唇,到底是詐尸還是另有隱情咐蝇,我是刑警寧澤,帶...
    沈念sama閱讀 35,460評(píng)論 5 344
  • 正文 年R本政府宣布巷查,位于F島的核電站有序,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏岛请。R本人自食惡果不足惜旭寿,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,070評(píng)論 3 327
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望崇败。 院中可真熱鬧许师,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,697評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至逞盆,卻和暖如春檀蹋,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背云芦。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,846評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工俯逾, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人舅逸。 一個(gè)月前我還...
    沈念sama閱讀 47,819評(píng)論 2 370
  • 正文 我出身青樓桌肴,卻偏偏與公主長(zhǎng)得像,于是被迫代替她去往敵國(guó)和親琉历。 傳聞我的和親對(duì)象是個(gè)殘疾皇子坠七,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,665評(píng)論 2 354

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