LayoutInflater作用是將layout的xml佈局文件實例化爲View類對象。
實現LayoutInflater的實例化共有3種方法,
(1).通過SystemService獲得
LayoutInflaterinflater = (LayoutInflater)context.getSystemServices(Context.LAYOUT_INFLATER_SERVICES);
Viewview = inflater.inflate(R.layout.main, null);
(2).從給定的context中獲得
LayoutInflaterinflater = LayoutInflater.from(context);
Viewview = inflater.inflate(R.layout.mian, null);
(3).
LayoutInflaterinflater =getLayoutInflater();(在Activity中可以使用,實際上是View子類下window的一個函數)
Viewlayout = inflater.inflate(R.layout.main, null);
其實,這三種方式本質是相同的,從源碼中可以看出:
getLayoutInflater():
Activity的getLayoutInflater()方法是調用PhoneWindow的getLayoutInflater()方法,看一下該源代碼:
publicPhoneWindow(Contextcontext) {
super(context);
mLayoutInflater= LayoutInflater.from(context);
}
可以看出它其實是調用LayoutInflater.from(context)。
LayoutInflater.from(context):
public static LayoutInflaterfrom(Context context) {
LayoutInflaterLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(LayoutInflater== null){
thrownew AssertionError("LayoutInflaternot found.");
}
returnLayoutInflater;
}
可以看出它其實調用context.getSystemService()。
public View inflate(int Resourece,ViewGrouproot)
作用:填充一個新的視圖層次結構從指定的XML資源文件中
reSource:View的layout的ID
root: 生成的層次結構的根視圖
return 填充的層次結構的根視圖。如果參數root提供了,那麼root就是根視圖;否則填充的XML文件的根就是根視圖。
其餘幾個重載的inflate函數類似。