LayoutInflater作用是將layout的xml布局文件實例化為View類對象。
對於一個沒有被載入或者想要動態載入的界面,都需要使用LayoutInflater.inflate()來找 res/layout下的 xml 布局文件,並且實例化為View類對象;
獲取LayoutInflater的方法有如下三種:
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = LayoutInflater.from(context); //該方法實質就是第一種方法 View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = getLayoutInflater(); //在Activity中可以使用,實際上是View子類下window的一個函數 View layout = inflater.inflate(R.layout.main, null);
·findViewById() 是找具體 xml 布局文件中的具體 widget 控件(如:Button、TextView 等)。