天天看点

正确使用inflate,inflate原理解析,LayoutInflater

要看结论直接拉到底部

在用代码inflate一个XML布局文件添加到父容器时,偶尔会碰到这个inflate出来的view,会无法正确显示我们在xml中所定义的样子,比如可能会无法正确显示最外层定义的参数,width,height,padding,margin等等。今天研究了下inflate的源码,总算明白了正确使用的姿势。

inflate一个xml布局文件有多种方式:比如可以调用View类的inflate方法,

public static View inflate (Context context, int resource, ViewGroup root)
           

还可以调用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);
    }
           

所以我们只要分析public View inflate (int resource, ViewGroup root, boolean attachToRoot)这一个方法就行了

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;

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

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

            } catch (XmlPullParserException e) {
                InflateException ex = new InflateException(e.getMessage());
                ex.initCause(e);
                throw ex;
            } catch (Exception e) {
                InflateException ex = new InflateException(
                        parser.getPositionDescription()
                                + ": " + e.getMessage());
                ex.initCause(e);
                throw ex;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;
            }

            Trace.traceEnd(Trace.TRACE_TAG_VIEW);

            return result;
        }
    }
           

挑重点看,第9行,这个方法的返回值初始化为我们传入的参数二:root,然后42行,根据参数一实例化了xml view,46行判断root是否为空,如果不为空,52行获取到了xml view的最外层布局参数LayoutParams,然后53行判断参数三是否为false,如果是false,将LayoutParams设置到xml view去。73行,判断root不为空,并且attachToRoot为true,实例化出来的xml view会被添加到root中去。79行有两个判断,如果root为空,返回值变为实例化出来的xml view,或者参数三attachToRoot为false,返回值变为实例化出来的xml view。

结论:

1:当root不为空并且attachToRoot为true时,返回的是root!!!(坑点一.....exo me???黑人问号脸)所以此方法返回的不一定就是实例化出来的xml view

2:当root为空时,实例化出来的xml view最外层的布局参数无效(坑点二.....exo me???黑人问号脸)

3:当root为空时,参数三已经无效,没意义了

4:调用重载方法,例如View.inflate (context, resource, root),root同时控制了attachToRoot参数,root不为空,attachToRoot为true,root为空,attachToRoot就为false(坑点三....)