Android 從源碼看懂窗口繪制流程

前言

Android開發(fā)最息息相關(guān)的就是界面,平時(shí)開發(fā)總會使用各種布局和視圖來組合成我們的屏幕效果,在Android的知識體系中戈鲁,View扮演著很重要的角色,簡單來理解嘹叫,View是Android在視覺上的呈現(xiàn)荞彼。那Android是如何將這些View一步步繪制到屏幕上的呢,這就涉及到本文所要講的窗口繪制工作原理待笑。

先上一張結(jié)構(gòu)圖鸣皂,帶著這張結(jié)構(gòu)圖去分析源碼:


Activity結(jié)構(gòu)圖

?

源碼分析

我們最經(jīng)常接觸的往往是View這一層,在它之上有Activity暮蹂,Activity一般都要在onCreate中調(diào)用setContentView寞缝,那就從setContentView進(jìn)去看究竟做了啥:

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

可以看到實(shí)際上是調(diào)用了getWindow得到的對象再去setContentView,所以其實(shí)在View和Activity中間還隔著一層Window仰泻,它是Activity與View之間的橋梁荆陆,是一個抽象類,PhoneWindow是它的唯一實(shí)現(xiàn)子類集侯,我們在Activity中所使用的View其實(shí)都是通過PhoneWindow來呈現(xiàn)的被啼,它就類似于View的一個載體,就像PS中的畫板棠枉,而View就是具體要繪制的內(nèi)容浓体。

那么PhoneWindow里面又是什么構(gòu)成呢?繼續(xù)順著剛才setContentView看進(jìn)去:

    @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();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            //忽略代碼
        } else {
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        //忽略代碼
    }

可以看到先是installDecor()辈讶,installDecor源碼如下:

private void installDecor() {
   if (mDecor == null) {
     //new一個DecorView
     mDecor = generateDecor();
     mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
     mDecor.setIsRootNamespace(true);
     if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
       mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
     }
   }
   if (mContentParent == null) {
     mContentParent = generateLayout(mDecor);
        }
        //忽略代碼
}

可以看到這里首先創(chuàng)建了一個DecorView命浴,然后調(diào)用generateLayout,詳細(xì)看下generateLayout:

protected ViewGroup generateLayout(DecorView decor) {
        //忽略代碼
        int layoutResource;
        ...
        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) {
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogTitleIconsDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else {
                layoutResource = R.layout.screen_title_icons;
            }
            ...
        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
                && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
            layoutResource = R.layout.screen_progress;
        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogCustomTitleDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else {
                layoutResource = R.layout.screen_custom_title;
            }
        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
            if (mIsFloating) {
                TypedValue res = new TypedValue();
                getContext().getTheme().resolveAttribute(
                        R.attr.dialogTitleDecorLayout, res, true);
                layoutResource = res.resourceId;
            } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
                layoutResource = a.getResourceId(
                        R.styleable.Window_windowActionBarFullscreenDecorLayout,
                        R.layout.screen_action_bar);
            } else {
                layoutResource = R.layout.screen_title;
            }
        } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
            layoutResource = R.layout.screen_simple_overlay_action_mode;
        } else {
            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;
}

可以看到先是根據(jù)feature類型來為layoutResource賦值,隨便選擇一個layout文件打開如下:

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

這個布局文件里最外層是一個LinearLayout生闲,里面還包含著一個id為R.id.content的FrameLayout媳溺,我們繼續(xù)回到代碼中,剛才賦值了layoutResource后碍讯,接著調(diào)用了DecorView的onResourcesLoaded悬蔽,先看下里面做了啥:

void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
        //...忽略代碼
        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;
        //...忽略代碼
    }

    @Override
    public void onDraw(Canvas c) {
        super.onDraw(c);

        // When we are resizing, we need the fallback background to cover the area where we have our
        // system bar background views as the navigation bar will be hidden during resizing.
        mBackgroundFallback.draw(isResizing() ? this : mContentRoot, mContentRoot, c,
                mWindow.mContentParent);
    }

可以看到這里將我們傳進(jìn)來的layoutResource資源inflate成了View,然后將其addViewDecorView自身并且在onDraw中繪制了出來捉兴,換句話說就是把剛才那個layout文件添加到DecorView中并繪制屯阀。
那么剛才那個layout文件用來做什么的呢?回到上一步轴术,onResroucesLoaded之后难衰,通過findViewById查找id為R.id.content的View(看到?jīng)],這里就是我們剛才那個layout文件中的R.id.content逗栽,所以實(shí)際上就是先將layout文件add到DecorView中去盖袭,然后再將其content給find出來),然后將其返回彼宠,賦值給剛才分析過的installDecor方法中的mContentParent鳄虱,然后現(xiàn)在回頭看回我們一開始的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();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            //忽略代碼
        } else {
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        //忽略代碼
    }

我們發(fā)現(xiàn)了mContentParent的影子!凭峡,mLayoutInflater.inflate(layoutResID, mContentParent);拙已,它將layoutResID的資源通過inflate添加到了我們的mContentParent(inflate的參數(shù)解讀見我另一篇文章:http://www.reibang.com/p/3f871d95489c

所以其實(shí)我們平時(shí)setContetntView傳進(jìn)去的R.layout.xxx最終都會添加到R.id.content這個View上面,這也就是為什么它命名為setContentView的原因了摧冀,而R.id.content又是被包裹在一層LinearLayout里面倍踪,然后這個LinearLayout文件又會被通過addView添加到DecorView這個FrameLayout中,原來 DecorView 就是承載了我們布局文件的一個頂級大佬索昂。

?

總結(jié)

現(xiàn)在再回過頭看文章開頭那個結(jié)構(gòu)圖建车,是否清晰了很多呢~這里只是從setContentView分析了從Activity到Window再到DecorView的層級和繪制流程,接下來還有關(guān)于View的繪制再慢慢總結(jié)椒惨,不得不說源碼里還是有很多值得借鑒的地方缤至,多看源碼對自己的理解會更有幫助,不能知其然不知其所以然康谆。

GitHubGitHub-ZJYWidget
CSDN博客IT_ZJYANG
簡 書Android小Y
在Github上建了一個集合炫酷自定義View的項(xiàng)目领斥,里面有很多實(shí)用的自定義View源碼及demo,會長期維護(hù)沃暗,歡迎Star~ 如有不足之處或建議還望指正月洛,相互學(xué)習(xí),相互進(jìn)步描睦,如果覺得不錯動動小手給個喜歡膊存, 謝謝~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末导而,一起剝皮案震驚了整個濱河市忱叭,隨后出現(xiàn)的幾起案子隔崎,更是在濱河造成了極大的恐慌,老刑警劉巖韵丑,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件爵卒,死亡現(xiàn)場離奇詭異,居然都是意外死亡撵彻,警方通過查閱死者的電腦和手機(jī)钓株,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來陌僵,“玉大人轴合,你說我怎么就攤上這事⊥攵蹋” “怎么了受葛?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長偎谁。 經(jīng)常有香客問我总滩,道長,這世上最難降的妖魔是什么巡雨? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任闰渔,我火速辦了婚禮,結(jié)果婚禮上铐望,老公的妹妹穿的比我還像新娘冈涧。我一直安慰自己,他們只是感情好正蛙,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布炕舵。 她就那樣靜靜地躺著,像睡著了一般跟畅。 火紅的嫁衣襯著肌膚如雪咽筋。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天徊件,我揣著相機(jī)與錄音奸攻,去河邊找鬼。 笑死虱痕,一個胖子當(dāng)著我的面吹牛睹耐,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播部翘,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼硝训,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起窖梁,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤赘风,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后纵刘,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體邀窃,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年假哎,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了瞬捕。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡舵抹,死狀恐怖肪虎,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情惧蛹,我是刑警寧澤笋轨,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站赊淑,受9級特大地震影響爵政,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜陶缺,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一钾挟、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧饱岸,春花似錦掺出、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至百框,卻和暖如春闲礼,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背铐维。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工柬泽, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人嫁蛇。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓锨并,卻偏偏與公主長得像,于是被迫代替她去往敵國和親睬棚。 傳聞我的和親對象是個殘疾皇子第煮,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,871評論 2 354

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