LayoutInflate.inflate(...)深入源碼分析

先上個(gè)圖:


LayoutInflate.inflate(...)

上圖是LayoutInflate.inflate(...)的每個(gè)重載的方法中參數(shù)的類(lèi)型茄菊,方法也不是很多缘眶,我們就一個(gè)個(gè)來(lái)看看他源碼是怎么樣子的翰舌。

那么我們先把這幾個(gè)參數(shù)是做什么用的解釋了,以便后面方法的理解:

  • int resource:布局文件xml的資源id
  • ViewGroup root:如果attchToRoot為true的話唤锉,root作為父布局
  • XmlPullParser parser:Android自帶的xml解析類(lèi)型世囊,產(chǎn)生DOM節(jié)點(diǎn)
  • boolean attachToRoot:是否加載到root布局中

源碼分析:

可以從紅色框框看到調(diào)用的是第一張圖片中第三個(gè)重載方法:

inflate(resource, root)

那么我們?nèi)タ纯茨莻€(gè)調(diào)用的方法又是如何實(shí)現(xiàn)的:

inflate(resource, root, attachToRoot)

從上圖代碼中,我么可以看到腌紧,其將傳入的xml布局解析成XmlResourceParser格式后茸习,調(diào)用了第一張圖片的第四個(gè)重載方法。在這里壁肋,根據(jù)第一個(gè)方法的return号胚,我們可以推測(cè)下,第二個(gè)方法是不是也是調(diào)用了第四個(gè)重載方法呢浸遗?現(xiàn)在就看源碼驗(yàn)證猫胁!

inflate(parser, root)

果然驗(yàn)證了我們的猜想,那么我們就來(lái)看看第四個(gè)重載方法跛锌,看看他的奧秘在哪里弃秆,先上源碼:

/**
  * 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);
        Context lastContext = (Context) mConstructorArgs[0];
        mConstructorArgs[0] = inflaterContext;
        View result = root;
        try {
            // Look for the root node.
            int type;
            while ((type = parser.next()) != XmlPullParser.START_TAG && type != XmlPullParser.END_DOCUMENT) {
                // Empty
            }
            if (type != XmlPullParser.START_TAG) {
                throw new InflateException(parser.getPositionDescription() + ": No start tag found!");
            }
            final String name = parser.getName();
            if (DEBUG) {
                System.out.println("**************************");
                System.out.println("Creating root view: "
                        + name);
                System.out.println("**************************");
            }
            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) {
                    if (DEBUG) {
                        System.out.println("Creating params from root: " +
                                root);
                    }
                    // Create layout params that match root, if supplied
                    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);
                    }
                }
                if (DEBUG) {
                    System.out.println("-----> start inflating children");
                }
                // Inflate all children under temp against its context.
                rInflateChildren(parser, temp, attrs, true);
                if (DEBUG) {
                    System.out.println("-----> done inflating children");
                }
                // We are supposed to attach all the views we found (int temp)
                // to root. Do that now.
                if (root != null && attachToRoot) {
                    root.addView(temp, params);
                }
                // Decide whether to return the root that was passed in or the
                // top view found in xml.
                if (root == null || !attachToRoot) {
                    result = temp;
                }
            }
        } catch (XmlPullParserException e) {
            InflateException ex = new InflateException(e.getMessage());
            ex.initCause(e);
            throw ex;
        } catch (Exception e) {
            InflateException ex = new InflateException(
                    parser.getPositionDescription()
                            + ": " + e.getMessage());
            ex.initCause(e);
            throw ex;
        } finally {
            // Don't retain static reference on context.
            mConstructorArgs[0] = lastContext;
            mConstructorArgs[1] = null;
        }
        Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        return result;
    }
}
判斷最外層是否是merge

可知道届惋,當(dāng)根節(jié)點(diǎn)是merge的時(shí)候,只能是在root != null && attachToRoot = true的時(shí)候菠赚,否者會(huì)報(bào)異常脑豹。

對(duì)父布局root判斷

紅色框中,返回的是xml布局的LayoutParams參數(shù)大小衡查。該方法是調(diào)用ViewGroup中方法來(lái)實(shí)例化獲得LayoutParams數(shù)據(jù)瘩欺。所以就是說(shuō),當(dāng)沒(méi)有傳遞root進(jìn)來(lái)的時(shí)候拌牲。就不能獲得xml布局中的大小參數(shù)俱饿。而接著當(dāng)attachToRoot為false的時(shí)候,將params賦給temp塌忽。

LayoutInflate.png

從上面代碼我們知道拍埠,當(dāng) root != null && attachToRoot為true的時(shí)候,將temp添加到root布局中返回(這里return的是result土居,但在方法的一開(kāi)始有將root賦給result枣购,這里root與result其實(shí)就是等價(jià)的了)。而當(dāng)root == null || attachToRoot為false的時(shí)候擦耀,將temp賦給result返回坷虑。說(shuō)明,當(dāng)root == null 的時(shí)候埂奈,attachToRoot設(shè)置true/false都是沒(méi)關(guān)系的。

對(duì)了定躏。連注釋都忘了解釋?zhuān)?/p>

方法注釋轉(zhuǎn)譯

最后總結(jié):

  • 若root = null账磺,則attachToRoot無(wú)所謂true/false,并不能獲得任何效果痊远,那么xml中最外層的布局的layout_width和layout_height設(shè)置將失效垮抗。
  • 若root != null && attachToRoot = false,不加載到root中碧聪,使得Layout文件中(最常用的例子就是adapter中的layout)最外層的布局的layout_width和layout_height設(shè)置將有效冒版。
  • 若root != null && attachToRoot = true,加載到root中逞姿,并將root返回辞嗡。

以上是個(gè)人學(xué)習(xí)觀點(diǎn),若有不恰當(dāng)或不正確的地方滞造,歡迎指正续室。一起學(xué)習(xí)。

hierarchy n. 層級(jí)谒养;等級(jí)制度

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末挺狰,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌丰泊,老刑警劉巖薯定,帶你破解...
    沈念sama閱讀 217,734評(píng)論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異瞳购,居然都是意外死亡话侄,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,931評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)苛败,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)满葛,“玉大人,你說(shuō)我怎么就攤上這事罢屈∴秩停” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 164,133評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵缠捌,是天一觀的道長(zhǎng)锄贷。 經(jīng)常有香客問(wèn)我,道長(zhǎng)曼月,這世上最難降的妖魔是什么谊却? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,532評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮哑芹,結(jié)果婚禮上炎辨,老公的妹妹穿的比我還像新娘。我一直安慰自己聪姿,他們只是感情好碴萧,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,585評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著末购,像睡著了一般破喻。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上盟榴,一...
    開(kāi)封第一講書(shū)人閱讀 51,462評(píng)論 1 302
  • 那天曹质,我揣著相機(jī)與錄音,去河邊找鬼擎场。 笑死羽德,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的顶籽。 我是一名探鬼主播玩般,決...
    沈念sama閱讀 40,262評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼礼饱!你這毒婦竟也來(lái)了坏为?” 一聲冷哼從身側(cè)響起究驴,我...
    開(kāi)封第一講書(shū)人閱讀 39,153評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎匀伏,沒(méi)想到半個(gè)月后洒忧,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,587評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡够颠,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,792評(píng)論 3 336
  • 正文 我和宋清朗相戀三年熙侍,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片履磨。...
    茶點(diǎn)故事閱讀 39,919評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡蛉抓,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出剃诅,到底是詐尸還是另有隱情巷送,我是刑警寧澤,帶...
    沈念sama閱讀 35,635評(píng)論 5 345
  • 正文 年R本政府宣布矛辕,位于F島的核電站笑跛,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏聊品。R本人自食惡果不足惜飞蹂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,237評(píng)論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望翻屈。 院中可真熱鬧陈哑,春花似錦、人聲如沸伸眶。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,855評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)赚抡。三九已至,卻和暖如春纠屋,著一層夾襖步出監(jiān)牢的瞬間涂臣,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,983評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工售担, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留赁遗,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,048評(píng)論 3 370
  • 正文 我出身青樓族铆,卻偏偏與公主長(zhǎng)得像岩四,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子哥攘,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,864評(píng)論 2 354

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

  • ¥開(kāi)啟¥ 【iAPP實(shí)現(xiàn)進(jìn)入界面執(zhí)行逐一顯】 〖2017-08-25 15:22:14〗 《//首先開(kāi)一個(gè)線程剖煌,因...
    小菜c閱讀 6,409評(píng)論 0 17
  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理材鹦,服務(wù)發(fā)現(xiàn),斷路器耕姊,智...
    卡卡羅2017閱讀 134,656評(píng)論 18 139
  • 簡(jiǎn)述 LayoutInfalter主要是用來(lái)加載布局桶唐。對(duì)LayoutInfalter不怎么熟悉的,通常都是在Act...
    PeterHe888閱讀 1,403評(píng)論 0 0
  • RecyclerView Item 布局寬高無(wú)效問(wèn)題探究 前言 這個(gè)問(wèn)題很早之前就碰到過(guò)茉兰,后來(lái)通過(guò)google找到...
    TinyMen閱讀 423評(píng)論 0 0
  • 有不少朋友跟我反應(yīng)规脸,都希望我可以寫(xiě)一篇關(guān)于View的文章坯约,講一講View的工作原理以及自定義View的方法。沒(méi)錯(cuò)莫鸭,...
    御風(fēng)之閱讀 438評(píng)論 0 3