LayoutInflater源码执行流程

一直以来开发Android都是通过xml文件布局页面,也听有些朋友说过一些公司为了性能不让使用xml布局,只能通过纯代码的方式写界面。通过纯代码的方式和xml布局的方式各有优略:

考虑性能当然纯代码更好,毕竟加载xml布局需要先读取文件,又要通过反射创建视图对象,效率自然没有纯代码高;但是就开发效率而言xml布局的方式更好,实时预览界面是非常大的优势,想想AndroidStudio跑一遍程序的耗时吧。

当然也有听说ios开发绝大部分人是使用纯代码绘制界面,于是了解了一下ios的情况,他们也有类似于xml布局的方式但是属性实在太多,又不像Android一样设计了各种容器类控件来适应不同的布局场景,写起来还不如纯代码来的方便。另外ios倒是有一个叫StoryBoard的东西,也可以直接拖动控件布局,但是这种方式需要把控件的事件逻辑也在StoryBoard添加,代码中会生成一个加了注解的事件方法,类似于Android的xml中控件直接加onClick,我们都知道这种方式查找方法和维护都比较麻烦。所以ios使用纯代码开发是有其客观原因的。

作为开发者我还是是倾向xml,毕竟是官方写法嘛,性能也不可能差太多,开发效率当然也很重要是吧。还是来看一下xml的加载过程吧

我们经常需要在代码中读取一个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源码设计模式解析与实战

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值