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

先上個圖:


LayoutInflate.inflate(...)

上圖是LayoutInflate.inflate(...)的每個重載的方法中參數的類型,方法也不是很多,我們就一個個來看看他源碼是怎么樣子的。

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

  • int resource:布局文件xml的資源id
  • ViewGroup root:如果attchToRoot為true的話,root作為父布局
  • XmlPullParser parser:Android自帶的xml解析類型,產生DOM節點
  • boolean attachToRoot:是否加載到root布局中

源碼分析:

可以從紅色框框看到調用的是第一張圖片中第三個重載方法:

inflate(resource, root)

那么我們去看看那個調用的方法又是如何實現的:

inflate(resource, root, attachToRoot)

從上圖代碼中,我么可以看到,其將傳入的xml布局解析成XmlResourceParser格式后,調用了第一張圖片的第四個重載方法。在這里,根據第一個方法的return,我們可以推測下,第二個方法是不是也是調用了第四個重載方法呢?現在就看源碼驗證!

inflate(parser, root)

果然驗證了我們的猜想,那么我們就來看看第四個重載方法,看看他的奧秘在哪里,先上源碼:

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

可知道,當根節點是merge的時候,只能是在root != null && attachToRoot = true的時候,否者會報異常。

對父布局root判斷

紅色框中,返回的是xml布局的LayoutParams參數大小。該方法是調用ViewGroup中方法來實例化獲得LayoutParams數據。所以就是說,當沒有傳遞root進來的時候。就不能獲得xml布局中的大小參數。而接著當attachToRoot為false的時候,將params賦給temp。

LayoutInflate.png

從上面代碼我們知道,當 root != null && attachToRoot為true的時候,將temp添加到root布局中返回(這里return的是result,但在方法的一開始有將root賦給result,這里root與result其實就是等價的了)。而當root == null || attachToRoot為false的時候,將temp賦給result返回。說明,當root == null 的時候,attachToRoot設置true/false都是沒關系的。

對了。連注釋都忘了解釋:

方法注釋轉譯

最后總結:

  • 若root = null,則attachToRoot無所謂true/false,并不能獲得任何效果,那么xml中最外層的布局的layout_width和layout_height設置將失效。
  • 若root != null && attachToRoot = false,不加載到root中,使得Layout文件中(最常用的例子就是adapter中的layout)最外層的布局的layout_width和layout_height設置將有效。
  • 若root != null && attachToRoot = true,加載到root中,并將root返回。

以上是個人學習觀點,若有不恰當或不正確的地方,歡迎指正。一起學習。

hierarchy n. 層級;等級制度

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,443評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,530評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,407評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,981評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,759評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,204評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,263評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,415評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,955評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,650評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,892評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,675評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,967評論 2 374

推薦閱讀更多精彩內容