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. 層級;等級制度

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容