LayoutInflater作用是將layout的xml布局文件實例化為View類對象。通俗的說, LayoutInflater的inflate函數就相當于將一個xml中定義的布局找出來,變成一個實例以供使用。
實例化LayoutInfater有三種方式:
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = LayoutInflater.from(context); //(該方法實質就是第一種方法,可參考源代碼)
LayoutInflater inflater = getLayoutInflater(); //(在Activity中可以使用,實際上是View子類下window的一個函數)
然后可以調用其inflate方法實例化xml文件了:
View layout = inflater.inflate(R.layout.main, null);
setContentView和inflate的區別:
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv);
LayoutInflater inflate = LayoutInflater.from(this);
View view = inflate.inflate(R.layout.main,null);
setContentView(view);
setContentView()一旦調用, layout就會立刻顯示UI;而inflate只會把Layout形成一個以view類實現成的對象,在有需要的時候再用setContentView(view)顯示出來。
比如一般在activity中通過setContentView()將界面顯示出來,但是如果在非activity中如何對控件布局設置操作了,這就需要LayoutInflater動態加載。
又比如如果你的Activity里如果用到別的layout,比如對話框的layout,而且你還要設置對話框上的layout里的組件(像圖片ImageView,文字TextView)上的內容,你就必須用inflate()先將對話框的layout找出來,然后再用這個layout對象去找到它上面的組件(使用這個layout對象的findViewById方法)