关于Android inflate三种参数的区别

时间过得真快,记得上次写博客的时候还在大三,现在已经大四了,其实有的时候也看看源码,但是有的时候比较懒惰,看懂之后,就懒得记下来了,结果好长时间之后都忘记了。

inflate传三种参数,我项大家都知道,那么有什么区别呢?
文本只研究内部执行的代码,适用于已经知道三种参数的区别,但不知道拥护啥的童鞋。

我先粘贴一下代码哈!
进入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();
final XmlResourceParser parser = res.getLayout(resource);

这个方法返回了一个XmlResourceParser 接口,从名字上来看就能明白,这个是xml解析器,不明白xml解析的同学请自行补习。其实这个接口的一系列方法都是用来解析XML文件的。
接下来调用 return inflate(parser, root, 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(" 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;
        }
    }

代码比较多,大家来慢慢的看:

 View result = root;

将我们根布局赋值给了result。

 final String name = parser.getName();

得到根结点的名字,后续会根据这个根结点的名字实现相对应的对象。

if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException(" can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } 

判断一下你这个根结点的名字是不是为merge,如果不知道什么是merge布局的同学请自行补习。

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

            }

这段代码是和上面那对if配对的,被我拆开来看了。

  final View temp = createViewFromTag(root, name, inflaterContext, attrs);

这段代码厉害喽,传递一个root,name,attrs

这句代码从官方提供的api文档的意思来看
//Creates a view from a tag name using the supplied attribute set.
从tag name和提供的属性集set创建一个View,这个name,就是之前调用parser.getName();等到的name,在这个方法里面我们看到了熟悉的代码:

 try {
            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('.')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;

onCreateView()方法,得到View,并且返回回来,回到刚才的代码我们继续往下面看:

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

大家来看看这段代码:

ViewGroup.LayoutParams params = null;

首先定义一个ViewGroup.LayoutParms,其实这个就是一个根布局的属性。
然后:

 if (root != null) {
 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);
    }
}

大家看看这个就是传入第二个参数(根布局)和第三个参数(boolean)的作用
如果传入的root不等于null,params = root.generateLayoutParams(attrs);就将params赋值,然后下面有一个判断:

if (!attachToRoot) {
      // Set the layout params for temp if we are not
      // attaching. (If we are, we use addView, below)
     temp.setLayoutParams(params);
}

这就是第三个参数的作用,如果你传递第三个参数为false,则设置这个根布局的属性,果然你要是设置成为了true,那么看一下翻译:
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
意思是,如果你对这个temp没有进行附加,也就是传递false,那么,就会对temp设置temp.setLayoutParams(params);否则使用addView,(below:看下面)
那么我们来看看下面指的什么:

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

这就是返回根不为null并且第三个参数传递的是true
将temp作为子孩子添加到root的下面。

让我们继续往下面看:

// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);

从给的解释来看:根据上下文对所有处于temp下的子View进行inflate。
我们来看看这个方法下面都干了写什么:

 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);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException(" cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException(" must be the root element");
            } else {
                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);
            }
        }

我们来看最后的一个else:

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

其实说白了这就是一个递归而已,把根结点底下的View都实例化,然后添加到ViewGroup里面。

接下来继续往下面看,如果第二个参数为null会怎么样:、

 if (root == null || !attachToRoot) {
     result = temp;
 }

从代码上很容易看出来,如果第二个参数为null,即使第三个参数传true或者false都是没有用的,都会将temp添加到result里面,并且返回。

说一下,我之前就是使用的这个参数,根目录传递一个null,第三个参数不穿,却发现加载出来的布局是包裹内容,也就是wrap_content,我查看我的xml文件里面,明明设置的宽和高都是match_parent结果布局文件里面的内容没有铺满全屏,因为第二个参数设置成了null,所以:

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

没有params = root.generateLayoutParams(attrs); 这句话,如果一个View或者ViewGroup没有指定属性,具体来说没有指定宽和高的情况下,比如你TextView tv=new TextView(getContext); 里面设置文字,会自动变成包裹内容的,所以我就遇到了上述出现的情况。

还有一个需要注意,如果第二个参数不为null,当第三个参数为false的情况下,所得到的布局不会包含root,如果第三个参数为true,则最后的布局会包括root。
关于Android inflate三种参数的区别_第1张图片

这张图片就是第三个参数为true的情况,其实从源码里面可以很清楚的看到:

if (root != null && attachToRoot) {
        root.addView(temp, params);
}

root.addView(),所以temp的上一级根是传递过来的root。
当我们第三个参数传递的是false的情况下,那么就不会运行上面那一段代码,而会运行

 if (!attachToRoot) {
 // Set the layout params for temp if we are not
         // attaching. (If we are, we use addView, below)
         temp.setLayoutParams(params);
}

只是将temp设置属性,rInflateChildren(parser, temp, attrs, true); 将temp底下的子View加进来,然后直接返回result(也就是temp),所以没有root这个根布局。
关于Android inflate三种参数的区别_第2张图片
最后:
本人写的比较墨迹,但是,我就喜欢写的墨迹点。
希望得到大家的建议,一起努力。

你可能感兴趣的:(动画)