对于LayoutInflater.from(parent.getContext()).inflate()方法的笔记

来源:互联网 发布:python循环读取文件 编辑:程序博客网 时间:2024/05/22 19:53
今天在练习的时候,,发现这里面两个方法的区别,给自己做点笔记

第一种,LayoutInflater.from(parent.getContext()) inflate(R.layout.item_layout, null);
第二种,LayoutInflater.from(parent.getContext())inflate(R.layout.item_layout, parent,false); 
item_layout的布局是这样的

这两个都是不会报错的,但是效果不一样,
第一种方式LayoutInflater.from(parent.getContext()) inflate(R.layout.item_layout, null);

第二种方式LayoutInflater.from(parent.getContext())inflate(R.layout.item_layout, parent,false); 


由上面的结果显示,里面的参数parent ,false着两个参数的含义,第一个,毋庸置疑,就是这个布局放在哪儿。就是这个parent
这个fasle 所对应的参数,源码里面是这么说的  Whether the inflated hierarchy should be attached to the root parameter? If false, root is only used to create the correct subclass of LayoutParams for the root view in the XML.google了一下,膨胀的层次结构是否应该附加到根参数? 如果为false,则root仅用于为XML中的根视图创建LayoutParams的正确子类。意思就是这个你在子布局中设置的属性是否添加到parent,如果设置为fasle,就是你在xml中设置成什么样就是什么样了,像上面我写的match_parent,它就占据parent的整个页面,不会再添加,当你设置为true的时候,他就报错了,java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first,说是这个页面已经有一个parent了。同理。当LayoutInflater.from(parent.getContext()) inflate(R.layout.item_layout, parent);的时候,会报同样的错。以此做个笔记

0 1