layoutInflater.inflate()方法似于findViewById()方法雷客,不同點(diǎn)是layoutInflater.inflate()是用來找res/layout/下的XML布局文件白嘁,并且實(shí)例化扶关;而findViewById()是找XML布局文件下的具體控件(如:Button、TextView等等)。
使用場(chǎng)景:
1篓足、對(duì)于一個(gè)沒有被載入或者想要?jiǎng)討B(tài)載入的界面,都需要使用layoutInflater.inflater()來載入界面闰蚕。
2栈拖、對(duì)于一個(gè)已經(jīng)載入的界面,可以使用activity.findViewById()來獲取界面中的控件没陡。
LayoutInflater
獲取LayoutInflater實(shí)例的3種方式:
// 1涩哟、在Activity中直接調(diào)用getLayoutInflater()來獲取
LayoutInflater inflater = activity.getLayoutInflater();
// 2、通過傳入context來獲取
LayoutInflater inflater = LayoutInflater.from(context);
// 3盼玄、調(diào)用Context的getSystemService()來獲取
LayoutInflater inflater =
(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
這3種方式本質(zhì)一樣贴彼,Activity的getLayoutInflater()方法中調(diào)用的是LayoutInflater.from(context)方法,而LayoutInflater.from(context)方法中調(diào)用的是context.getSystemService()方法埃儿,所以最終都是調(diào)用context.getSystemService()方法器仗。
layoutInflater.inflate()
一般有如下2種方法可供選擇
1、View inflate (int resource, ViewGroup root)
2、View inflate (int resource, ViewGroup root, boolean attachToRoot)
其中精钮,第1個(gè)參數(shù)resource表示要加載的XML布局文件威鹿;第2個(gè)參數(shù)root表示再套上一個(gè)父容器root,如果不需要就傳null轨香;第3個(gè)參數(shù)attachToRoot表示是否將當(dāng)前加載的布局套上一個(gè)父容器忽你。
注意:如果使用第1種只含2個(gè)參數(shù)的方法傳入了一個(gè)root就表示給布局再套上一個(gè)父容器root,attachToRoot默認(rèn)為true臂容。
使用layoutInflater.inflate()加載布局
View view = getLayoutInflater().inflate(R.layout.button_layout, null);