【Android 源碼解析】LayoutInflater 加載解析機(jī)制

LayoutInflater 實(shí)例化獲取方法

1、一般我們獲取 LayoutInflater 對(duì)象都是通過(guò) LayoutInflater 的 from 方法

public static LayoutInflater from(Context context) {
        LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (LayoutInflater == null) {
            throw new AssertionError("LayoutInflater not found.");
        }
        return LayoutInflater;
}

內(nèi)部封裝了 getSystemService 方法,
2挑格、我們也可以直接通過(guò)
LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
來(lái)獲取
3衷畦、Activity 也提供了 getLayoutInflater 方法阵谚,內(nèi)部是調(diào)用的 Window 類的 getLayoutInflater 方法鸟蟹,歸根到底還是通過(guò) getSystemService 來(lái)獲取泣洞。

LayoutInflater 的 View inflate(…) 方法族剖析

得到 LayoutInflater 對(duì)象之后我們就是傳遞 xml 然后解析得到 View
inflate 的重載方法有四個(gè):

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root)
public View inflate(XmlPullParser parser, @Nullable ViewGroup root)
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

根據(jù)第一個(gè)參數(shù)的區(qū)別全庸,上面四個(gè)方法可以分為兩組秀仲,第一組傳入的參數(shù)是 int 類型的資源文件 ID,第二組傳入的是一個(gè)XmlPullParser 對(duì)象壶笼,而其實(shí)傳入布局 ID 后神僵,也是被解析成了 XmlPullParser 對(duì)象,然后調(diào)用參數(shù)為 XmlPullParser 的重載方法:

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

因?yàn)?layout 文件也是資源文件的一種覆劈,所以可以用Resources 的 getLayout 方法獲取保礼,返回的就是 XmlpullParser 對(duì)象沛励。
兩個(gè)參數(shù)的方法內(nèi)部會(huì)調(diào)用三個(gè)參數(shù)的方法:

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

前面部分是從 XmlPullParser 中解析屬性,然后判斷布局文件的根標(biāo)簽是不是 merge炮障,如果是 merge 的話目派,第二個(gè)參數(shù)不能為 null,并且第三個(gè)參數(shù)必須為 true胁赢。因?yàn)?merge 只能作為 xml 文件的根元素企蹭,在 View 樹(shù)中必須加載在其它 ViewGroup 里。
接下來(lái)判斷第二個(gè)參數(shù) root 是否為 null智末,如果 root 不為 null谅摄,根據(jù)從 xml 文件中解析出來(lái)的 AttributeSet 中的 layout_width 和 layout_height 屬性生成 LayoutParams,如果第三個(gè)參數(shù) attachToRoot 為 true吹害,那么把解析出來(lái)的 View 根據(jù)生成的 LayoutParams 添加到 root 上螟凭,最后返回 root;如果為 false它呀,那么只是把 LayoutParams 設(shè)置給解析出來(lái)的 View,并返回 View棒厘。
如果 root 為 null纵穿,那么直接返回解析出來(lái)的 View。
兩個(gè)參數(shù)的 inflate 方法中第三個(gè)參數(shù)的值是取決于第二個(gè)參數(shù)的奢人,如果 root == null谓媒,那么 attachToRoot 默認(rèn)為 false,反之 attachToRoot 默認(rèn)為 true何乎。
總結(jié)一下就是:

  • inflate(xmlId,null) 等價(jià)于 inflate(xmlld,null,false)句惯,只創(chuàng)建 temp 的 View 并直接返回 temp,不能正確處理我們?cè)O(shè)置的寬和高支救;
  • inflate(xmlId,root) 等價(jià)于 inflate(xmlId,root,true)抢野,創(chuàng)建 View,執(zhí)行 root.addView(temp,params)各墨,返回 root指孤,能正確處理我們?cè)O(shè)置的寬和高;
  • inflate(xmlId,null,true) 贬堵,只創(chuàng)建 temp 的 View 并直接返回temp恃轩,不能正確處理我們?cè)O(shè)置的寬和高;
  • inflate(xmlId,root,false)黎做,創(chuàng)建 View叉跛,執(zhí)行 temp.setLayoutParams(params),返回 temp蒸殿,能正確處理我們?cè)O(shè)置的寬和高筷厘;

簡(jiǎn)單說(shuō)就是 root 不為 null挽铁,會(huì)生成 LayoutParams,xml 文件中設(shè)置的寬高有效敞掘,如果這時(shí)候 attchToRoot 為true叽掘,把解析出來(lái)的 View 添加到 root 上面返回 root
View 也有 inflate 方法,其實(shí)也是封裝了生成 LayoutInfalter 調(diào)用 inflate 方法:

public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

在 inflate 方法里面的細(xì)節(jié)并沒(méi)有作深入探討玖雁。
1.解析 XML 的根標(biāo)簽更扁。
2.如果是 merge,調(diào)用 rInflate 進(jìn)行解析赫冬。它會(huì)把 merge 所有子 view 添加到根標(biāo)簽中浓镜。
3.如果是普通標(biāo)簽,調(diào)用 createViewFromTag 進(jìn)行解析劲厌。
4.調(diào)用 rInflate 解析 temp 根元素下的子 view膛薛。并添加到 temp 中。

參考:
Android應(yīng)用setContentView與LayoutInflater加載解析機(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)店門寇漫,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(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)容