android inflate详解

作者: brzhang | 来源:发表于2016-06-07 17:01 被阅读1914次

我们在写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

相关文章

  • getViewById和getLayoutInflater().

    Android getViewById和getLayoutInflater().inflate()的详解及比较 这...

  • android inflate详解

    我们在写adapter的时候,经常会撸出这样的代码: 不知道为啥第三个参数要传false 那么看一下inflate...

  • [基础] inflate()

    inflate 参见:inflate()方法详解和源码分析方法一:public View inflate(int ...

  • Android知识杂记

    关于LayoutInflater inflate方法 root attachToRoot 参数详解[https:/...

  • inflate详解

    生成布局的时候,经常会用到LayoutInflater.from(context).inflate(layoutR...

  • 月笔记(2018-3)

    解决android.view.View android.view.ViewStub.inflate()' on a...

  • Understanding Android's Layo

    理解Android的LayoutInflater.inflate()方法 [Android 官方文档](http:...

  • Layout

    LayoutInflater.inflate()使用详解https://www.jianshu.com/p/c92...

  • LayoutInflater 参数详解

    1.inflate 的 参数详解 resource : 资源文件root :父节点attachToRoot : 表...

  • Android inflate解析

    Android inflate解析 对于inflate,我相信大家都不陌生,它的作用是将一个layout.xml布...

网友评论

    本文标题:android inflate详解

    本文链接:https://www.haomeiwen.com/subject/nigddttx.html