LayoutInflater流程

来源:互联网 发布:mac高光 编辑:程序博客网 时间:2024/06/16 23:19

LayoutInflater流程

    • LayoutInflater流程
      • 概述
      • 源码分析
      • 总结

概述

我们知道LayoutInflater的主要作用是从XML文件中加载布局,其主要是掉用inflate方法来加载布局。一般是通过如下方法使用:

LayoutInflater.from(context).inflate(R.layout.xxxx, this);LayoutInflater.from(context).inflate(R.layout.xxxx, null);LayoutInflater.from(context).inflate(R.layout.xxxx, root view,false);LayoutInflater.from(context).inflate(R.layout.xxxx, root view,true);

接下来从源码的角度来分析LayoutInflater加载布局的流程。


源码分析

首先来看获取LayoutInflater实例的方法。

  1. LayoutInflater.from()
public static LayoutInflater from(Context context) {        // 从系统服务中获取LayoutInflater        LayoutInflater LayoutInflater =                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);        if (LayoutInflater == null) {            throw new AssertionError("LayoutInflater not found.");        }        return LayoutInflater;    }

从xml加载布局的方法是inflate方法,这个方法被重载了,有多种实现。

  1. LayoutInflater.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();        // xml资源解析器        final XmlResourceParser parser = res.getLayout(resource);        try {            return inflate(parser, root, attachToRoot);        } finally {            parser.close();        }}

上面的方法最终都会调用到下面inflate方法,该方法是真正加载xml布局的方法。

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;            // 先将root View保存起来            View result = root;            try {                // 1.查找根节点                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!");                }                // 获取标签的名字,例如merge                final String name = parser.getName();                ....                // 2. 如果是merge标签                if (TAG_MERGE.equals(name)) {                    // root view为空,或者attchToRoot为false则抛出异常                    if (root == null || !attachToRoot) {                        throw new InflateException("<merge /> can be used only with a valid "                                + "ViewGroup root and attachToRoot=true");                    }                    // 3.递归方法,解析子元素                    rInflate(parser, root, inflaterContext, attrs, false);                } else {                    // 4.将从指定的name创建View,并把暂存到temp中                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);                    // View的参数                    ViewGroup.LayoutParams params = null;                    // 如果root view不为空,则根据root view来确定创建view的参数                    if (root != null) {                        // 5.根据root view来确定创建view的参数                        params = root.generateLayoutParams(attrs);                        // 6.如果attachToRoot为false,则将params参数设置给创建的View                        if (!attachToRoot) {                            temp.setLayoutParams(params);                        }                    }                    // 7. 递归加载创建的View下的所有子View                    rInflateChildren(parser, temp, attrs, true);                    // 8. 如果root View不为空,并且attachToRoot为true,则将创建的View添加的root view中                    if (root != null && attachToRoot) {                        root.addView(temp, params);                    }                    // 9.如果root View为空,或者attachToRoot为false,则直接返回已创建的View。                    if (root == null || !attachToRoot) {                        result = temp;                    }                }            } catch (XmlPullParserException e) {              // 异常处理               .....            } finally {                mConstructorArgs[0] = lastContext;                mConstructorArgs[1] = null;            }            // 返回结果            return result;        }    }

在inflate方法中,通过xml解析器出根节点标签,然后通过根节点标签去创建View。根据root View以及attachToRoot的组合取值,决定view的处理流程。具体如下面的表格所示:

root view attachToRoot 说明 null NA 返回xml加载的View 非null false 返回xml加载的View,并将root View的参数应用到xml加载的View中 非null true 返回root View,并把xml加载的View添加到root View中

接着通过rInflateChildren方法递归解析子View,最后返回创建的View。

根据标签创建View是通过createViewFromTag方法实现的。

3.LayoutInflater.createViewFromTag()

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,            boolean ignoreThemeAttr) {        if (name.equals("view")) {            name = attrs.getAttributeValue(null, "class");        }        // Apply a theme wrapper, if allowed and one is specified.        if (!ignoreThemeAttr) {            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);            final int themeResId = ta.getResourceId(0, 0);            if (themeResId != 0) {                context = new ContextThemeWrapper(context, themeResId);            }            ta.recycle();        }        ......        try {            View view;            // 如果定了创建View的工厂,则使用工厂方法来创建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);            }            if (view == null) {                final Object lastContext = mConstructorArgs[0];                mConstructorArgs[0] = context;                try {                    if (-1 == name.indexOf('.')) {                        // 1.如果是系统view,例如TextView                        view = onCreateView(parent, name, attrs);                    } else {                        // 2.自定义View,例如com.android.MyTextView                        view = createView(name, null, attrs);                    }                } finally {                    mConstructorArgs[0] = lastContext;                }            }            return view;        } catch (InflateException e) {            // 异常处理        }    }

从上面可以看到,如果是系统原生的控件,则调用onCreateView方法来创建View。如果是自定义的View,则调用createView方法来创建View。

创建系统View的方法如下:

protected View onCreateView(View parent, String name, AttributeSet attrs)            throws ClassNotFoundException {        return onCreateView(name, attrs);}protected View onCreateView(String name, AttributeSet attrs)            throws ClassNotFoundException {            //创建以android.view开头的View,例如TextView    return createView(name, "android.view.", attrs);}

创建自定义View的方法如下:

public final View createView(String name, String prefix, AttributeSet attrs)            throws ClassNotFoundException, InflateException {        Constructor<? extends View> constructor = sConstructorMap.get(name);        if (constructor != null && !verifyClassLoader(constructor)) {            constructor = null;            sConstructorMap.remove(name);        }        Class<? extends View> clazz = null;        try {            if (constructor == null) {                // Class not found in the cache, see if it's real, and try to add it                // 通过ClassLoader加载Class对象                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 {                .....            }            // 获取构造器参数            Object[] args = mConstructorArgs;            args[1] = attrs;            // 通过反射创建View对象            final View view = constructor.newInstance(args);            // 如果View是ViewStub,则使用相同的context来加载ViewStub            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) {           ....        } finally {            Trace.traceEnd(Trace.TRACE_TAG_VIEW);        }    }

可以看到,不管是原生系统的View还是自定义的View都是通过反射来创建View对象。

4.LayoutInflater.rInflateChildren
rInflateChildren方法是一个递归方法,用来加载子View的。

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 {        // 解析的深度        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);            // 解析include标签            } else if (TAG_INCLUDE.equals(name)) {                if (parser.getDepth() == 0) {                    throw new InflateException("<include /> cannot be the root element");                }                parseInclude(parser, context, parent, attrs);            // merge标签必须出现在根节点中,不能出现在子节点中            } else if (TAG_MERGE.equals(name)) {                throw new InflateException("<merge /> must be the root element");            } else {                // 根据标签名创建View,例如TextView                final View view = createViewFromTag(parent, name, context, attrs);                // 保存父View以及父view的参数                final ViewGroup viewGroup = (ViewGroup) parent;                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);                // 递归调用加载子View                rInflateChildren(parser, view, attrs, true);                // 将子View添加到父View中                viewGroup.addView(view, params);            }        }        // 解析完成        if (finishInflate) {            parent.onFinishInflate();        }}

可以看到rInflateChildren方法就是递归去解析子View,并把子View添加到父View中。这样就完成了整个View树的加载。

LayoutInflater加载xml布局文件的总体流程如下:

LayoutInflater.inflate()    LayoutInflater.createViewFromTag()        LayoutInflater.rInflateChildren()

总结

LayoutInflater技术广泛用于动态加载View,在使用LayoutInflater来加载View时,需要注意参数root和attachToRoot的使用,它们之间的不同组合将产生不同的结果。

  1. 如果root为null,attachToRoot将失去作用,只返回创建的View,不能正确处理宽和高,因为layout_width和layout_height都是相对于父View设置的。
  2. 如果root不为null,attachToRoot为true,则创建View,并把创建的View添加到root View中,最后返回root View。
  3. 如果root不为null,attachToRoot为false,则创建View,并把root View的参数params应用到创建的View中,返回创建的View。
原创粉丝点击