我們在寫adapter的時(shí)候,經(jīng)常會擼出這樣的代碼:
@Overridepublic TagViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag, parent, false);
return new TagViewHolder(view);}
不知道為啥第三個(gè)參數(shù)要傳false
那么看一下inflate的源碼,我們大致就能了解這些個(gè)參數(shù)有些什么作用了。
- 如果root為null,attachToRoot將失去作用,設(shè)置任何值都沒有意義。
- 如果root不為null,attachToRoot設(shè)為true,則會給加載的布局文件的指定一個(gè)父布局,即root。
- 如果root不為null,attachToRoot設(shè)為false,則會將布局文件最外層的所有l(wèi)ayout屬性進(jìn)行設(shè)置,當(dāng)該view被添加到父view當(dāng)中時(shí),這些layout屬性會自動生效。
- 在不設(shè)置attachToRoot參數(shù)的情況下,如果root不為null,attachToRoot參數(shù)默認(rèn)為true。
出自Android LayoutInflater原理分析,帶你一步步深入了解View(一)
所以更具以上結(jié)論來看,如果我們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 這些布局屬性起作用的話,你應(yīng)該如此擼代碼:
LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tag, parent, false);

Paste_Image.png