于 2016 年 08 月 19 日

  • 走了一遍 LayoutInflater的流程,特此记录
      • 获取 LayoutInflater --- LayoutInflater.from(context)
      • 调用Inflate -- LayoutInflater.from(context).inflate(R.layout.activity_layout,null,false)
      • inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)是整个inflate的核心部分
        • 首先是看第一部分,父布局temp的实例化
        • 然后是子布局的实例化

走了一遍 LayoutInflater的流程,特此记录

获取 LayoutInflater --- LayoutInflater.from(context)

获取LayoutInflater对象实例

​```
    public static LayoutInflater from(Context context) {
        //获取 layoutInflater,注意这是一个IPC的过程,获取的实例是PhoneLayoutInflater,与LayoutInflater 区别不大,重写了protected View onCreateView(String name, AttributeSet attrs) 函数,具体可以去看源码,位置是frameworks/base/core/java.com.android.internal.policy.impl
            LayoutInflater LayoutInflater =
                    (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        //如果为空抛出错误       
            if (LayoutInflater == null) {
                throw new AssertionError("LayoutInflater not found.");
            }
        //返回值
                    return LayoutInflater;
    }
​```

调用Inflate -- LayoutInflater.from(context).inflate(R.layout.activity_layout,null,false)

​```
 public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
        //获取resource对象
        final Resources res = getContext().getResources();
        ...
        //把R.layout.activity_layout 放入,获取整个 Xml的Parser
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            // 开始真正的inflate
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
​```

inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)是整个inflate的核心部分

整体流程:

找到最外层的父级布局 ===》 处理merge节点情况 ===》实例化父级布局 =》根据父级布局,调用rInflate函数去实例化子级view=> 根据实例化结果,以及外部参数,进行view的添加以及结果的返回

​```
    public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
        //同步进入
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
            // 解析返回 attrs
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            // 
            Context lastContext = (Context)mConstructorArgs[0];
            mConstructorArgs[0] = mContext;
            // 传入的 viewgroup 是 null
            View result = root;
            try {
                // 此处尝试寻找开始和结束节点,即找到整个layout的最外层 view
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                // 如果 type != 开始节点抛出错误,也就是说没找到开始节点
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            * ": No start tag found!");
                }
                // 获取当前节点的名字,也就是当前layout的根节点的名字
                final String name = parser.getName();

                ...
                //处理 merge 节点
                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");
                    }
                    rInflate(parser, root, attrs, false, false);
                } else {// 不是merge的情况下
                    // createViewFromTag 该方法是根据前面获取的 tag 的名字,创建具体的view对象
                    // 此处特殊的地方时,Temp 就是根节点,也就是整个layout的根节点,因为 name 是前面获取的根节点的名字
                    final View temp = createViewFromTag(root, name, attrs, false);
                    // 初始化 params
                    ViewGroup.LayoutParams params = null;
                    if (root != null) {// root != 空,会初始化出一个 params

                        ...
                        // 如果提供了root,会根据 root 创建 layout params 
                        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);
                        }
                    }
                    ...
                    // 此处,会进行所有的 temp 的子 view 的 inflate
                    rInflate(parser, temp, attrs, true, true);

                    ...
                    // 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) {
                ...
            } catch (IOException e) {
                ...
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;
            }
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            return result;
        }
    }
​```

其中整个流程中,核心部分分两点

1.实例化父级布局,

2.实例化子级view

而对于merge节点的处理情况是将其当做子view进行处理,调用的都是rInflate函数,所以,我们讨论子view实例化的时候可以一起讨论。

首先是看第一部分,父布局temp的实例化。

他是直接调用createViewFromTag,我们进入该函数。这个函数整体的流程是

处理特殊节点view ===》 对当前view的context进行初始化 ====》 特殊节点blink处理 ===》根据几个工厂对象(默认情况下,工程类都为null)实例化view ===》 工厂类创建失败,view == null,调用onCreateView()或者createView()view进行实例化

​```
     View createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext) {
        // 特殊处理 `view` 节点
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }
        // 设置当前 view 的 context
        Context viewContext;
        if (parent != null && inheritContext) {
            // 如果父级 view 不为空 并且要求从父级 view 那里获取 context
            viewContext = parent.getContext();
        } else {
            // 否则 当前 view 的 context 等于 LayoutInflater.fromt(context) 中传入的 context
            viewContext = mContext;
        }
        // 如果有主题切换,那么就应用对应的主题
        final TypedArray ta = viewContext.obtainStyledAttributes(attrs, ATTRS_THEME);
        final int themeResId = ta.getResourceId(0, 0);
        if (themeResId != 0) {
            viewContext = new ContextThemeWrapper(viewContext, themeResId);
        }
        ta.recycle();
        // blink 处理
        if (name.equals(TAG_1995)) {
            // Let's party like it's 1995!
            return new BlinkLayout(viewContext, attrs);
        }
        ...
        try {
            // 用工厂类创建真正的 view 对象
            // 默认两个工厂类都为 null
            // 所以 view 是 null
            View view;
            if (mFactory2 != null) {
                view = mFactory2.onCreateView(parent, name, viewContext, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, viewContext, attrs);
            } else {
                view = null;
            }
            // 在 view 用前面两个工厂类创建为 null 
            // 同时私有工厂类不为空的情况下,调用私有的工厂类创建 view 对象
            if (view == null && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, viewContext, attrs);
            }
            // 私有工厂创建依旧为 null 时
            if (view == null) {
                final Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = viewContext;
                try {
                    if (-1 == name.indexOf('.')) {// 如果是 Android 自带 view
                        view = onCreateView(parent, name, attrs);
                    } else {// 如果不是 Android 自带 view
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }
            ...
            return view;
        } catch (InflateException e) {
            ...
        } catch (ClassNotFoundException e) {
            ...
        } catch (Exception e) {
            ...
        }
    }
​```

其中这个函数的核心部分则是onCreateView()createView(),因为默认情况下,几个factory都是null,所以都会进入这两个函数中的一个。

​```
    if (-1 == name.indexOf('.')) {// 如果是 Android 自带 view
        view = onCreateView(parent, name, attrs);
    } else {// 如果不是 Android 自带 view
        view = createView(name, null, attrs);
    }
​```

两个函数调用条件是,-1 == name.indexOf('.'),而其效果则是,判断是否为Android自带 view,如果是,则调用onCreateView(),否则当做自定义view处理,调用createView()

先看onCreateView,该部分主要是对sClassPrefixList进行迭代,拼凑出整个view的路径,然后调用createView(),注意这个函数,和上面说的处理自定义viewcreateView(),是同一个函数,所以也就明白,为什么要有上面的判断了

​```
    private static final String[] sClassPrefixList = {
        "android.widget.",
        "android.webkit.",
        "android.app."
    };
     ....
     ....
     @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
        for (String prefix : sClassPrefixList) {
            try {
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {
                ...
            }
        }
        return super.onCreateView(name, attrs);
    }
​```

然后我们看真正的动态创建出view对象的函数createView(String name, String prefix, AttributeSet attrs),该函数的作用就是,通过反射创建出真正的对象

其过程也很简单,直接在已经存在的sConstructorMap中找,是不是有这个名字,如果有就开始创建,没有就把前缀拼上去,再创建,然后放入sConstructorMap

​```
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);
                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;
            constructor.setAccessible(true);
            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) {
            ...
        } catch (ClassCastException e) {
            ...
        } catch (ClassNotFoundException e) {
            ...
        } catch (Exception e) {
            ...
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }
​```

然后是子布局的实例化

该部分内容,主要是对当前节点的所有view 进行遍历,然后调用createViewFromTag()(该方法上面已经有解释了)方法创建实例。如果遍历到某一个view,他是有子节点的,则递归调用函数rInflate()对该子节点进行遍历。该部分参考下面的流程图,看起来更加清晰。

​```
    void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
            boolean finishInflate, boolean inheritContext) 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");
                }
                parseInclude(parser, parent, attrs, inheritContext);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                final View view = createViewFromTag(parent, name, attrs, inheritContext);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflate(parser, view, attrs, true, true);
                viewGroup.addView(view, params);
            }
        }
        if (finishInflate) parent.onFinishInflate();
    }
​```

以上就是 inflate 整个核心部分。

对于整体的流程,我画了流程图,如下

img

补充,迁移过程中原始图片已丢失