原文鏈接:點擊打開鏈接
===============================================================================================
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是多大呢?,最後也就只能包裹內容了.