android inflate详解

我们在写adapter的时候,经常会撸出这样的代码:

@Overridepublic TagViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {    
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag, parent, false);    
    return new TagViewHolder(view);}

不知道为啥第三个参数要传false

那么看一下inflate的源码,我们大致就能了解这些个参数有些什么作用了。

  1. 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
  2. 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
  3. 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。
  4. 在不设置attachToRoot参数的情况下,如果root不为null,attachToRoot参数默认为true。
    出自Android LayoutInflater原理分析,带你一步步深入了解View(一)

所以更具以上结论来看,如果我们item的布局是酱紫的:

<?xml version="1.0" encoding="utf-8"?>
<TextView    
   xmlns:android="http://schemas.android.com/apk/res/android"    
   android:padding="5dp"    
   android:layout_gravity="center"    
   android:gravity="center_horizontal"    
   android:layout_width="200dp"    
   android:layout_height="wrap_content">
</TextView>

如果你想让 android:layout_width 这些布局属性起作用的话,你应该如此撸代码:

  LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag, parent, false);
Paste_Image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

友情链接更多精彩内容