我们在写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的源码,我们大致就能了解这些个参数有些什么作用了。
- 如果root为null,attachToRoot将失去作用,设置任何值都没有意义。
- 如果root不为null,attachToRoot设为true,则会给加载的布局文件的指定一个父布局,即root。
- 如果root不为null,attachToRoot设为false,则会将布局文件最外层的所有layout属性进行设置,当该view被添加到父view当中时,这些layout属性会自动生效。
- 在不设置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);
![](https://img.haomeiwen.com/i1019822/6508fae8a6c28813.png)
网友评论