关于inflate的几个方法解析(结合日志源码)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shayubuhuifei/article/details/82862980

inflate使我们使用频率极高的api了,并且他有多个重载的方法,如下:

View inflate(int, ViewGroup)   
View inflate(XmlPullParser, ViewGroup)   
View inflate(int, ViewGroup, boolean)   
View inflate(XmlPullParser, ViewGroup, boolean)

我们要在不同的使用场景下,进行介绍。

  1. 我们一般不使用传入XmlPullParser解析器的方法,一般都是直接传入XML文件,方法内部会将XML转换成解析器,代码如下:
    final XmlResourceParser parser = res.getLayout(resource);

  1. 剩余的两个方法主要是最后一个参数(attachToRoot)是否传入的区别,其实两个参数的方法,最终会调用到三个参数的方法,代码如下:
 public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
        return inflate(parser, root, root != null);
    }

只不过最后一个参数是根据root是否为null来决定的,这也比较好理解,如果你没有传入root本身就没有父view可绑定,所以attachToRoot自然是false

  1. 介绍View inflate(int, ViewGroup) 方法,第二个参数是否传入null,所产生的不同的结果。

    1. Fragment中使用,在onCreateView中
     @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            LogUtils.d("-----"+container.toString());
            View inflate = inflater.inflate(R.layout.fragment, container);
            return inflate;
        }
        //如上使用会报错:Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
        
        //因为container不为null,原因是创建Fragment的时候,系统会默认给Fragment添加一个FrameLayout的父布局,如果这个时候在把Fragment加入到Activity中的布局时,就会报错了
        
        //打印的日志也证明上面的说法   09-26 04:36:16.725 350-350/test.juyoufuli.com.testapplication D/TestApplication: -----android.widget.FrameLayout{774b98b V.E..... ......ID 0,0-0,0 #7f070041 app:id/fl}
    
    

    如何正确使用呢? 两种方案:

        View inflate = inflater.inflate(R.layout.fragment, null);
         View inflate = inflater.inflate(R.layout.fragment, container,false);
         //根据源码可知,root传入null和attachToRoot传入false等价
    
    1. 其他常规用法基本原则是不变的,如下面代码:
            FrameLayout viewById = findViewById(R.id.fl);
            View inflate = getLayoutInflater().inflate(R.layout.fragment,null);
            LogUtils.d("-----"+inflate.getParent().toString());
            viewById.addView(inflate);
            //如上代码空指针错误,inflate.getParent()为null,常规填充是不会有父view的。
    
  2. 继续介绍传入不同的第三个参数,view会有不同的显示效果,源码的中的关键代码:

    /**
     * @param root Optional view to be the parent of the generated hierarchy (if
     * <em>attachToRoot</em> is true), or else simply an object that
     * provides a set of LayoutParams values for root of the returned
     *hierarchy (if <em>attachToRoot</em> is false.)
    */ 
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;
            View result = root;

            try {
               //主要部分
                if (TAG_MERGE.equals(name)) {
                //如果root为null或者不绑定到root,则布局效果都是按照父view的来的
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    // 这个传入的xml的根视图
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                    ViewGroup.LayoutParams params = null;
                    if (root != null) {
                        // Create layout params that match root, if supplied
                        //获取传入的父视图的布局参数
                        params = root.generateLayoutParams(attrs);
                        //初始化出来的子view不绑定到root上,则设置指定父布局的参数(算是一组参考的布局参数),后续需要自己调用addview方法,并且并不一定必须add到这个布局上
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

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

                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    //如果绑定到root上的话,就直接通过addview来加入到root的布局
                    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.
                    // 未指定父布局或者不绑定的话直接返回解析好view
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

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

                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            return result;
        }
    }

上面的注解也还算详细了,如有问题望各位大佬指点。

如上基本完成分析,下面总结一下使用的注意事项。

  1. 在绑定view的时候要注意是inflate出来的view已经默认添加了父view
  2. 如果还不确定要添加到的view,直接传入null即可,会减少一些计算逻辑
  3. 如果attachToRoot传入true,则不可以在调用addview方法,将该view添加到其他view上

猜你喜欢

转载自blog.csdn.net/shayubuhuifei/article/details/82862980