LayoutInflater源碼執行流程

我們經常需要在代碼中讀取一個xml文件將其對應的View加載到內存中,一般有兩種方式:


1.View.inflate(.......);
2.LayoutInflater.from(context).inflate(......);

第一種方式實際上內部也是通過LayoutInflater.from(context).inflate(......)實現的

    public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
        LayoutInflater factory = LayoutInflater.from(context);
        return factory.inflate(resource, root);
    }
我們先看一下LayoutInflater.from(context),它返回了LayoutInflater對象,LayoutInflater是一個抽象類,它實際上是其子類PhoneLayoutInflater對象,PhoneLayoutInflater主要重寫了onCreateView(String name, AttributeSet attrs)兩個參數的方法。PhoneLayoutInflater具體來源可以參考app啓動時註冊各項Service源碼,註冊LAYOUT_INFLATE_SERVICE是會通過PolicyManage創建,這裏不再詳述。

 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;
    }
inflate的重載方法最終都會調用到LayoutInflater下面這個inflate方法

   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資源解析器對象,並將其傳入到重載的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 result = root;////接收父View對象


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


                //判斷根節點是否爲merge類型
                if (TAG_MERGE.equals(name)) {
                    //當根節點爲merge類型且父view不爲空時解析xml
                    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;


                    //如果父view不爲null結合父view生成並設置LayoutParams
                    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");
                    }


                    //解析並加載所有子View
                    // 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) {
             ...
            }


            Trace.traceEnd(Trace.TRACE_TAG_VIEW);


            return result;
        }
    }
可以看到這個重載的inflate方法會檢查xml根節點是否爲merge類型,如果是則調用rInflate(parser, root, inflaterContext, attrs, false)直接以傳入的父View (root)爲根佈局解析merge標籤內部的子View。如果不是Merge類型,則調用createViewFromTag(root, name, inflaterContext, attrs)解析根節點View並結合父view生成並設置LayoutParams,最後再調用rInflateChildren(parser, temp, attrs, true)解析並加載所有子View。

我們先看一下createViewFromTag方法創建根佈局

	View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
                           boolean ignoreThemeAttr) {
        ...
		try {
            View view;
            //判斷有無設置自定義的Factory來創建View(我們一般都不設置)
            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);
            }


            //跳到這裏,通過調用onCreateView(parent, name, attrs)方法創建View對象
            //onCreateView在子類PhoneLayoutInflater中被重寫
            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    //判斷節點名是否包含“.”,不包含說明是系統定義的View
                    //主要是用於PhoneLayoutInflater中被重寫的兩個參數的onCreateView給View加上合適的全限定名
                    if (-1 == name.indexOf('.')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }


            return view;
        } catch (InflateException e) {
       ...
    }
這個方法內主要是判斷節點名是否是全限定名,如果不是就補全全限定名,再調用createView(String name, String prefix, AttributeSet attrs)通過反射真正的創建View。

public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        Constructor<? extends View> constructor = sConstructorMap.get(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
                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);
                    }
                }
                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;


            final View view = constructor.newInstance(args);
            if (view instanceof ViewStub) {
                // Use the same context when inflating ViewStub later.
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            return view;


        } catch (NoSuchMethodException e) {
        ...
        }
    }
至此,最外層不爲merge的情況下,根佈局視圖成功創建。

回到兩個解析子View的方法,非merge下調用rInflateChildren(parser, temp, attrs, true)最後也會與merge下調用相同的方法rInflate(parser, root, inflaterContext, attrs, false)開始解析流程。

final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
                                boolean finishInflate) throws XmlPullParserException, IOException {
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
void rInflate(XmlPullParser parser, View parent, Context context,
                  AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        //獲取xml深度
        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)) {//解析include標籤
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                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);//此方法內部調用了本方法
                viewGroup.addView(view, params);
            }
        }


        if (finishInflate) {
            parent.onFinishInflate();
        }
    }
此方法通過深度優先遍歷xml文件節點,遞歸調用本方法創建View根據父View生成並設置LayoutParams添加到父View中,從而完成整個xml視圖樹的構建。


參考:Android 6.0源碼、Android源碼設計模式解析與實戰


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