View 繪制體系知識(shí)梳理(1) - LayoutInflater#inflate 源碼解析

前幾天在通過(guò)LayoutInflater渲染出子布局,并添加進(jìn)入父容器的時(shí)候,出現(xiàn)了子布局的寬高屬性不生效的情況,為此,總結(jié)一下和LayoutInflater相關(guān)的知識(shí)。

一、獲得LayoutInflater

Android當(dāng)中,如果想要獲得LayoutInflater實(shí)例,一共有以下3種方法:

1.1 LayoutInflater inflater = getLayoutInflater();

這種在Activity里面使用,它其實(shí)是調(diào)用了

    /**
     * Convenience for calling
     * {@link android.view.Window#getLayoutInflater}.
     */
    @NonNull
    public LayoutInflater getLayoutInflater() {
        return getWindow().getLayoutInflater();
    }

下面我們?cè)賮?lái)看一下Window的實(shí)現(xiàn)類(lèi)PhoneWindow.java

    public PhoneWindow(Context context) {
        super(context);
        mLayoutInflater = LayoutInflater.from(context);
    }

它其實(shí)就是在構(gòu)造函數(shù)中調(diào)用了下面1.2的方法。
而如果是調(diào)用了Fragment中也有和其同名的方法,但是是隱藏的,它的理由是:

    /**
     * @hide Hack so that DialogFragment can make its Dialog before creating
     * its views, and the view construction can use the dialog's context for
     * inflation.  Maybe this should become a public API. Note sure.
     */
    public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
        final LayoutInflater result = mHost.onGetLayoutInflater();
        if (mHost.onUseFragmentManagerInflaterFactory()) {
            getChildFragmentManager(); // Init if needed; use raw implementation below.
            result.setPrivateFactory(mChildFragmentManager.getLayoutInflaterFactory());
        }
        return result;
    }

1.2 LayoutInflater inflater = LayoutInflater.from(this);

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

可以看到,它其實(shí)是調(diào)用了1.3,但是加上了判空處理,也就是說(shuō)我們從1.1當(dāng)中的Activity1.2方法中獲取的LayoutInflater不可能為空。

1.3 LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

這三種實(shí)現(xiàn),默認(rèn)最終都是調(diào)用了最后一種方式。

二、LayoutInflater#inflate

inflater一共有四個(gè)重載方法,最終都是調(diào)用了最后一種實(shí)現(xiàn)。

2.1 (@LayoutRes int resource, @Nullable ViewGroup root)

    /**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     * 
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @param root Optional view to be the parent of the generated hierarchy.
     * @return The root View of the inflated hierarchy. If root was supplied,
     *         this is the root View; otherwise it is the root of the inflated
     *         XML file.
     */
    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }

該方法,接收兩個(gè)參數(shù),一個(gè)是需要加載的xml文件的id,一個(gè)是該xml需要添加的布局,根據(jù)root的情況,返回值分為兩種:

  • 如果root == null,那么返回這個(gè)root
  • 如果root != null,那么返回傳入xml的根View

2.2 (XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

    /**
     * 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.
     * @return The root View of the inflated hierarchy. If root was supplied,
     *         this is the root View; otherwise it is the root of the inflated
     *         XML file.
     */
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
        return inflate(parser, root, root != null);
    }

它的返回值情況和2.1類(lèi)似,不過(guò)它提供的是不是xmlid,而是XmlPullParser,但是由于View的渲染依賴(lài)于xml在編譯時(shí)的預(yù)處理,因此,這個(gè)方法并不合適。

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

    /**
     * Inflate a new view hierarchy from the specified xml resource. Throws
     * {@link InflateException} if there is an error.
     * 
     * @param resource ID for an XML layout resource to load (e.g.,
     *        <code>R.layout.main_page</code>)
     * @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(@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();
        }
    }

如果我們需要渲染的xmlid類(lèi)型的,那么會(huì)先把它解析為XmlResourceParser,然后調(diào)用2.4的方法。

2.4 public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

    /**
     * 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) {
            final Context inflaterContext = mContext;
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;
            try {.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                //1.如果根節(jié)點(diǎn)的元素不是START_TAG,那么拋出異常。
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }
                final String name = parser.getName();
                //2.如果根節(jié)點(diǎn)的標(biāo)簽是<merge>,那么必須要提供一個(gè)root,并且該root要被作為xml的父容器。
                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");
                    }
                    //2.1遞歸地調(diào)用它所有的孩子.
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    //temp表示傳入的xml的根View
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    //如果提供了root并且不需要把xml的布局加入到其中,那么僅僅需要給它設(shè)置參數(shù)就好。
                    //如果提供了root并且需要加入,那么不會(huì)設(shè)置參數(shù),而是調(diào)用addView方法。
                    if (root != null) {
                        //如果提供了root,那么產(chǎn)生參數(shù)。
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }
                    //遞歸地遍歷孩子.
                    rInflateChildren(parser, temp, attrs, true);
                    if (root != null && attachToRoot) {
                        //addView時(shí)需要加上前面產(chǎn)生的參數(shù)。
                        root.addView(temp, params);
                    }
                    //如果沒(méi)有提供root,或者即使提供root但是不用將root作為parent,那么返回的是渲染的xml,在`root != null && attachToRoot`時(shí),才會(huì)返回root。
                    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;
            }
            return result;
        }
    }

我們簡(jiǎn)單總結(jié)一下英文注釋當(dāng)中的說(shuō)明,具體的流程可以看上面的中文注釋。

  • 作用:從特定的xml節(jié)點(diǎn)渲染出一個(gè)新的view層級(jí)。
  • 提示:為了性能考慮,不應(yīng)當(dāng)在運(yùn)行時(shí)使用XmlPullParser來(lái)渲染布局。
  • 參數(shù)parser:包含有描述xml布局層級(jí)的parser xml dom。
  • 參數(shù)root,可以是渲染的xmlparentattachToRoot == true),或者僅僅是為了給渲染的xml層級(jí)提供LayoutParams
  • 參數(shù)attachToRoot:渲染的View層級(jí)是否被添加到root中,如果不是,那么僅僅為xml的根布局生成正確的LayoutParams。
  • 返回值:如果attachToRoot為真,那么返回root,否則返回渲染的xml的根布局。

三、不指定root的情況

由前面的分析可知,當(dāng)我們沒(méi)有傳入root的時(shí)候,LayoutInflater不會(huì)調(diào)用temp.setLayoutParams(params),也就是像之前我遇到問(wèn)題時(shí)的使用方式一樣:

LinearLayout linearLayout = (LinearLayout) mLayoutInflater.inflate(R.layout.linear_layout, null);
mContentGroup.addView(linearLayout);

當(dāng)沒(méi)有調(diào)用上面的方法時(shí),linearLayout內(nèi)部的mLayoutParams參數(shù)是沒(méi)有被賦值的,下面我們?cè)賮?lái)看一下,通過(guò)這個(gè)返回的temp參數(shù),把它通過(guò)不帶參數(shù)的addView方法添加進(jìn)去,會(huì)發(fā)生什么。
調(diào)用addView后,如果沒(méi)有指定index,那么會(huì)把index設(shè)為-1,按前面的分析,那么下面這段邏輯中的getLayoutParams()必然是返回空的。

    public void addView(View child, int index) {
        if (child == null) {
            throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
        }
        LayoutParams params = child.getLayoutParams();
        if (params == null) {
            params = generateDefaultLayoutParams();
            if (params == null) {
                throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
            }
        }
        addView(child, index, params);
    }

在此情況下,為它提供了默認(rèn)的參數(shù),那么,這個(gè)默認(rèn)的參數(shù)是什么呢?

protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}

也就是說(shuō),當(dāng)我們通過(guò)上面的方法得到一個(gè)View樹(shù)之后,將它添加到某個(gè)布局中,這個(gè)View數(shù)所指定的根布局中的寬高屬性其實(shí)是不生效的,而是變?yōu)榱?code>LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容