LayoutInflater

2020-07-23  本文已影响0人  还是昵称啊

LayoutInflater

LayoutInflatre能将一个xml文件解析成对应的View并构建对应的View的关系结构。使用这个类在需要的时候才解析一个布局文件,来避免一开始就加载xml布局文件造成资源浪费。

1. 使用方法

LayoutInflater inflater = LayoutInflater.from(this);
View inflatedLayout = inflater.inflate(R.layout.inflate_layout, mParent, false);

首先通过静态方法传入一个上下文对象获取一个LayoutInflater实例,然后调用inflate方法来解析这个布局文件。这个方法传入三个参数:

2. 源码分析

2.1

View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
if (view != null) {
    return view;
}
XmlResourceParser parser = res.getLayout(resource);
try {
    return inflate(parser, root, attachToRoot);
} finally {
    parser.close();
}

先判断是否已经解析过该文件,如果已经解析过直接返回解析出来的View,否则就将资源文件准换成一个XmlResourceParser对象,然后调用inflate方法;

2.2

Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;

try {
    advanceToRootNode(parser);
    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)) {
        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;

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

        // 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;
        }
    }
  

这个方法用于对不同的标签类型来执行不同的解析策略,最终把返回一个解析出来的View.在解析过程中主要由以下几个步骤:

上一篇 下一篇

猜你喜欢

热点阅读