LayoutInflater源碼分析

前言

最近又遇到RecyclerView的item最外層佈局參數失效的問題,之前都沒有去了解真正的原因,現在正好有空探尋一下這個問題,就從瞭解源碼開始吧。

View的inflate()

平時我經常使用View.inflate(),它是View的一個靜態方法,看到源碼:

   public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }

其中調用了LayoutInflater的靜態方法from()

    /**
     * Obtains the LayoutInflater from the given context.
     */
    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;
    }

這裏根據上下文,從系統獲取了一個LayoutInfalter的實例對象。

LayoutInflater的infalte()

然後接着上面,用這個獲取的對象去調用LayoutInfalter的inflate():

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }

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

其中可以看到獲取了一個xml解析器,獲取解析器的時候把要填充的xml的ID作爲了參數,然後又去調用了一個inflate()的重載:

    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, 即方法參數root
            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)) {
                    // 如果要填充的xml根佈局爲merge標籤
                    if (root == null || !attachToRoot) {
                        // 如果root爲空或者不需要將創建出來的View添加到root中直接會拋異常
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    // 創建並填充子View
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    // 根據xml,創建對應的View,叫temp
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        // 如果傳進來的root不爲空
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        // Create layout params that match root, if supplied
                        // 那麼根據xml中配置的屬性,去獲取佈局參數
                        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不需要被添加到root中,就給他設置佈局參數
                            temp.setLayoutParams(params);
                        }
                    }

                    if (DEBUG) {
                        System.out.println("-----> start inflating children");
                    }

                    // Inflate all children under temp against its context.
                    // 創建並填充子View
                    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不爲空,並且temp需要被添加到root中
                        // 那就把temp添加到root中
                        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) {
                        // root爲空或者temp不需要被添加到root中
                        // 那麼該方法返回的View就是temp
                        // 否則返回root
                        result = temp;
                    }
                }

            } catch (XmlPullParserException e) {
                final InflateException ie = new InflateException(e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } catch (Exception e) {
                final InflateException ie = new InflateException(parser.getPositionDescription()
                        + ": " + e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;

                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            return result;
        }
    }

以上的這個方法信息量很大,我寫了很多中文註釋在代碼中。

關於方法返回值

我們可以知道,如果root爲空或者我當前要創建的View不需要添加到root中,那麼返回的就是我要創建的View,反之返回的是root。

外層佈局失效的問題

我寫的代碼是這樣的View view = View.inflate(context, R.layout.item_pic, null);,然後根據函數調用鏈:

// 第一步:
View view = View.inflate(context, R.layout.item_pic, null);
// 第二步
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
    // 就變成了infalte(R.layout.item_pic, null, false);
    return inflate(resource, root, root != null);
}
……
// 最後就進入了上面的方法
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot){
    ……
}

因爲我最初傳入的root就是空啊,所以我最後只是創建了View,返回了View 但是沒有給他設置佈局參數,所以出現外層佈局失效的問題。

那我創建RecyclerView的item時,直接把RecyclerView作爲參數root傳進去可以嗎?答案是不行的,因爲這樣的話調用inflate()的時候是這樣的:inflate(resource, recyclerView, true)。然後你創建了View,並且把它添加到了RecyclerView。然而RecyclerView接收到你返回的View之後,還會自動把它添加到本身,這樣又會出現重複添加的問題

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first

最佳解決方案就是直接使用LayoutInflater:View view = LayoutInflater.from(context).inflate(R.layout.item_pic, recyclerView, false);
這樣的話,回去看下inflate()中的邏輯,發現view會被設置佈局參數,並且不會直接被添加到recyclerView中。

LayoutInflater的createViewFromTag()

在inflate()中使用createViewFromTag()去創建xml對應的View,以下是主要代碼:

    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        ……
        try {
            View view;
            // 可以設置LayoutInflater的Factory來自行解析View,默認這些Factory都爲空
            if (mFactory2 != null) {
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }

            if (view == null && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }

            if (view == null) {
                // 沒有Factory的情況下,通過LayoutInflater的onCreateView()或者createView()去創建View
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    if (-1 == name.indexOf('.')) {
                        // 創建原生的View
                        // 會在onCreateView()的函數調用鏈中補充前綴"android.view."
                        // 最終也會調用createView()
                        view = onCreateView(parent, name, attrs);
                    } else {
                        // 創建自定義View
                        // 我們在xml裏寫的都是全類名,標籤中包含"."
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
        } 
        ……
    }

以上說到的Factory,我之前在TintContextWrapper強轉Activity失敗原因深度探索分析到過,當我們使用AppCompatActivity時,會設置Factory2爲AppCompatViewInflater,然後View都會走AppCompatViewInflatercreateView()

LayoutInflater的createView():

     /**
     * Low-level function for instantiating a view by name. This attempts to
     * instantiate a view class of the given <var>name</var> found in this
     * LayoutInflater's ClassLoader.
     * 
     * <p>
     * There are two things that can happen in an error case: either the
     * exception describing the error will be thrown, or a null will be
     * returned. You must deal with both possibilities -- the former will happen
     * the first time createView() is called for a class of a particular name,
     * the latter every time there-after for that class name.
     * 
     * @param name The full name of the class to be instantiated.
     * @param attrs The XML attributes supplied for this instance.
     * 
     * @return View The newly instantiated view, or null.
     */
   public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        // 從緩存中獲取View的構造函數
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class<? extends View> clazz = null;

        try {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);

            if (constructor == null) {
                // 如果緩存中沒有需要的構造函數
                // Class not found in the cache, see if it's real, and try to add it
                // 如果prefix不爲空,那麼構造完整View路徑,並且加載該類
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);

                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
                // 從Class對象中獲取構造函數
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                // 將構造函數存入緩存中
                sConstructorMap.put(name, constructor);
            } else {
                // If we have a filter, apply it to cached constructor
                if (mFilter != null) {
                    // Have we seen this name before?
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) {
                        // New class -- remember whether it is allowed
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);

                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
            }

            Object[] args = mConstructorArgs;
            args[1] = attrs;

            // 通過反射構造View
            final View view = constructor.newInstance(args);
            if (view instanceof ViewStub) {
                // Use the same context when inflating ViewStub later.
                // 如果是ViewStub,延遲加載
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            return view;

        }
        ……
    }

對於創建View使用反射其實我比較疑惑,方法註釋說的是這個createView()是低版本上使用的方法,用來從類加載器中加載給定的View。後來我百度了下,可能是爲了實現全局換膚這種類似的操作。

LayoutInflater的rInflate()

通過createViewFromTag()創建了View之後,只是創建了根佈局的View,那其中的子View呢,回顧inflate()中的代碼,我們會發現rInflate()rInflateChildren()這兩個方法,rInflateChildren()調用的還是rInflate()

    void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        // 獲取樹的深度
        final int depth = parser.getDepth();
        int type;
        // 深度優先遍歷
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();

            // 解析標籤
            if (TAG_REQUEST_FOCUS.equals(name)) {
                parseRequestFocus(parser, parent);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                // 解析inclued標籤
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                // merge標籤只能是根佈局
                // 到了這裏說明不是根佈局,拋出異常
                throw new InflateException("<merge /> must be the root element");
            } else {
                // 創建View
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                // 創建佈局參數
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                // 遞歸地去遍歷子樹
                rInflateChildren(parser, view, attrs, true);
                // 將創建的View加入父佈局
                viewGroup.addView(view, params);
            }
        }

        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

佈局優化總結

從以上的源碼分析,我們其實可以得出如下結論:

  1. merge標籤作爲填充的xml的根佈局時,必須指定一個父元素並且設置attachToRoot屬性爲true。

  2. 我們通常使用ViewStub來做預加載處理,來改善頁面加載速度和提高流暢性。

  3. include標籤用來複用佈局。

在分析源碼到用反射創建View的時候,我發現了一篇比較不錯的文章Android 中LayoutInflater(佈局加載器)系列博文說明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章