View 繪製體系知識梳理(1) LayoutInflater#inflate 源碼解析

前幾天在經過LayoutInflater渲染出子佈局,並添加進入父容器的時候,出現了子佈局的寬高屬性不生效的狀況,爲此,總結一下和LayoutInflater相關的知識。java

1、得到LayoutInflater

Android當中,若是想要得到LayoutInflater實例,一共有如下3種方法:node

1.1 LayoutInflater inflater = getLayoutInflater();

這種在Activity裏面使用,它實際上是調用了android

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

下面咱們再來看一下Window的實現類PhoneWindow.javabash

public PhoneWindow(Context context) {
        super(context);
        mLayoutInflater = LayoutInflater.from(context);
    }
複製代碼

它其實就是在構造函數中調用了下面1.2的方法。 而若是是調用了Fragment中也有和其同名的方法,可是是隱藏的,它的理由是:dom

/**
     * @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;
    }
複製代碼

能夠看到,它實際上是調用了1.3,可是加上了判空處理,也就是說咱們從1.1當中的Activity1.2方法中獲取的LayoutInflater不可能爲空。ide

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

這三種實現,默認最終都是調用了最後一種方式。函數

2、LayoutInflater#inflate

inflater一共有四個重載方法,最終都是調用了最後一種實現。佈局

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);
    }
複製代碼

該方法,接收兩個參數,一個是須要加載的xml文件的id,一個是該xml須要添加的佈局,根據root的狀況,返回值分爲兩種:性能

  • 若是root == null,那麼返回這個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相似,不過它提供的是否是xmlid,而是XmlPullParser,可是因爲View的渲染依賴於xml在編譯時的預處理,所以,這個方法並不合適。ui

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類型的,那麼會先把它解析爲XmlResourceParser,而後調用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.若是根節點的元素不是START_TAG,那麼拋出異常。
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }
                final String name = parser.getName();
                //2.若是根節點的標籤是<merge>,那麼必需要提供一個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遞歸地調用它全部的孩子.
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    //temp表示傳入的xml的根View
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    //若是提供了root而且不須要把xml的佈局加入到其中,那麼僅僅須要給它設置參數就好。
                    //若是提供了root而且須要加入,那麼不會設置參數,而是調用addView方法。
                    if (root != null) {
                        //若是提供了root,那麼產生參數。
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            temp.setLayoutParams(params);
                        }
                    }
                    //遞歸地遍歷孩子.
                    rInflateChildren(parser, temp, attrs, true);
                    if (root != null && attachToRoot) {
                        //addView時須要加上前面產生的參數。
                        root.addView(temp, params);
                    }
                    //若是沒有提供root,或者即便提供root可是不用將root做爲parent,那麼返回的是渲染的xml,在`root != null && attachToRoot`時,纔會返回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; } } 複製代碼

咱們簡單總結一下英文註釋當中的說明,具體的流程能夠看上面的中文註釋。

  • 做用:從特定的xml節點渲染出一個新的view層級。
  • 提示:爲了性能考慮,不該當在運行時使用XmlPullParser來渲染布局。
  • 參數parser:包含有描述xml佈局層級的parser xml dom
  • 參數root,能夠是渲染的xmlparentattachToRoot == true),或者僅僅是爲了給渲染的xml層級提供LayoutParams
  • 參數attachToRoot:渲染的View層級是否被添加到root中,若是不是,那麼僅僅爲xml的根佈局生成正確的LayoutParams
  • 返回值:若是attachToRoot爲真,那麼返回root,不然返回渲染的xml的根佈局。

3、不指定root的狀況

由前面的分析可知,當咱們沒有傳入root的時候,LayoutInflater不會調用temp.setLayoutParams(params),也就是像以前我遇到問題時的使用方式同樣:

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

當沒有調用上面的方法時,linearLayout內部的mLayoutParams參數是沒有被賦值的,下面咱們再來看一下,經過這個返回的temp參數,把它經過不帶參數的addView方法添加進去,會發生什麼。 調用addView後,若是沒有指定index,那麼會把index設爲-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);
    }
複製代碼

在此狀況下,爲它提供了默認的參數,那麼,這個默認的參數是什麼呢?

protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
複製代碼

也就是說,當咱們經過上面的方法獲得一個View樹以後,將它添加到某個佈局中,這個View數所指定的根佈局中的寬高屬性實際上是不生效的,而是變爲了LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT

相關文章
相關標籤/搜索