LayoutInflater大家都用很久了,但是有時候有些小問題比如inflate出來的view屬性沒有生效等等都困擾着大家;又比如在自定義的adapter裏面inflate的佈局文件高度沒辦法設定等等,參考了一些文章和文檔,這裏做一些筆記,希望大家都能補充。
LayoutInflater.inflate()的作用就是將一個xml定義的佈局文件實例化爲view控件對象;
與findViewById區別:
LayoutInflater.inflate是加載一個佈局文件;
findViewById則是從佈局文件中查找一個控件;
一.獲取LayoutInflater對象有三種方法
LayoutInflater inflater=LayoutInflater.from(context);
LayoutInflater inflater=getLayoutInflater();在Activity中可以使用,實際上是View子類下window的一個函數
LayoutInflater inflater=(LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
二:inflate 參數
public View inflate(int resource, ViewGroup root, boolean attachToRoot) :
reSource:View的layout的ID
root:需要附加到resource資源文件的根控件,inflate()會返回一個View對象,如果第三個參數attachToRoot爲true,就將這個root作爲根對象返回,否則僅僅將這個root對象的LayoutParams屬性附加到resource對象的根佈局對象上,也就是佈局文件resource的最外層的View上。如果root爲null則會忽略view根對象的LayoutParams屬性(注意)。
attachToRoot:是否將root附加到佈局文件的根視圖上
例子:
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.fragment, root,false);
或者:
v = inflater.inflate(R.layout.fragment, null);
常見問題:
有時候我們在Adapter加載自定義的view佈局文件,佈局文件中設置了android:layout_height="100dip",但是運行程序後發現一點作用都沒有,相似的還有layout_width等以android:layout_開頭的屬性設置都沒有作用;
因爲Adapter裏有一個方法是getView,這個返回的VIew是一個從XML佈局里加載的,一般如下:
View v = inflater.inflate(R.layout.fragment, null);
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
代碼中可以發現:當root爲null的時候是不會執行params = root.generateLayoutParams(attrs);這段代碼的,這段代碼就是把xml裏的佈局配置轉爲LayoutParams,換句說就是加載我們配置的佈局屬性,以供佈局類(FrameLayout等)在onLayout的時候控制View的大小、位置、對齊等等。。以FrameLayout爲例,看下它的generateLayoutParams(attrs)方法。