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)方法。