inflate(int resource, ViewGroup root, boolean attachToRoot)
第一個參數傳入布局的資源ID,生成fragment視圖,第二個參數是視圖的父視圖,通常我們需要父
視圖來正確配置組件。第三個參數告知布局生成器是否將生成的視圖添加給父視圖。
root不為空的情況:
1.如果attachToRoot為true,就直接將這個布局添加到root父布局了,並且返回的view就是父布局
2.如果attachToRoot為false,就不會添加這個布局到root父布局,返回的view為resource指定的布局
root為空的情況:
View view = View.inflate(context, R.layout.button_layout, null);
其實等價於:LayoutInflater.from(this).layoutInflater.inflate(R.layout.button_layout, null);
那么root為不為空有什么影響呢?
1.如果root為null,attachToRoot將失去作用,設置任何值都沒有意義。同時這個布局的最外層參數就沒有效了
2.如果root不為null,attachToRoot設為false,則會將布局文件最外層的所有layout屬性進行設置,
當該view被添加到父view當中時,這些layout屬性會自動生效。
3.如果root不為null,attachToRoot設為true,則會給加載的布局文件的指定一個父布局,即root。
其實View必須存在於一個父布局中,這樣layout_width和layout_height才會有效,
這也是為什么這兩個屬性叫作layout_width和layout_height,而不是width和height。
所以:inflate(int resource, ViewGroup root, boolean attachToRoot)的第二個參數不為空,resource的最外層布局參數才會有效,否則就無效了
例子:item的布局文件如下
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="100dp"> <TextView android:id="@+id/textView" android:textSize="30sp" android:gravity="center" android:background="#ffcccc" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>
如果我是這樣加載這個布局:
View view= LayoutInflater.from(context).inflate(R.layout.recycler_item_layout,parent,false);
效果如下: 可見在item布局中設置的寬高都有效
如果我是這樣加載布局:
View view = View.inflate(context, R.layout.recycler_item_layout, null);
效果圖如下: 可見在item設置的寬高都無效,如果你在LinearLayout中設置寬高的長度為固定值100dp,這樣也是沒有效果的,但是如果是在TextView中設置寬高為固定值,這樣是有效的
原因也就是layout_height是在父布局中的高度,你要是都沒有父布局,它又怎么能知道你的match_parent是多大呢?,最后也就只能包裹內容了.