天天看點

LayoutInflater和inflate()方法的用法

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函數類似。