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

澤毛發表於2017-12-21

前幾天在通過LayoutInflater渲染出子佈局,並新增進入父容器的時候,出現了子佈局的寬高屬性不生效的情況,為此,總結一下和LayoutInflater相關的知識。

一、獲得LayoutInflater

Android當中,如果想要獲得LayoutInflater例項,一共有以下3種方法:

1.1 LayoutInflater inflater = getLayoutInflater();

這種在Activity裡面使用,它其實是呼叫了

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

下面我們再來看一下Window的實現類PhoneWindow.java

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

它其實就是在建構函式中呼叫了下面1.2的方法。 而如果是呼叫了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;
    }
複製程式碼

可以看到,它其實是呼叫了1.3,但是加上了判空處理,也就是說我們從1.1當中的Activity1.2方法中獲取的LayoutInflater不可能為空。

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

這三種實現,預設最終都是呼叫了最後一種方式。

二、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在編譯時的預處理,因此,這個方法並不合適。

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的根佈局。

三、不指定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

相關文章