LayoutInflater與findViewById的區別?
- 對于一個已經載入的界面,就可以使用findViewById()方法來獲得其中的界面元素。
- 對于一個沒有被載入或者想要動態載入的界面,就需要使用
LayoutInflater
對象的inflate()
方法來載入。 - findViewById()是查找已被實例化為View對象的xml布局文件下的具體控件(如Button、TextView等),操作對象是一個ViewGroup或者是Activity,返回一個View對象。
LayoutInflater
實例的inflate()
方法是用來將res/layout/
下的xml布局文件實例化,操作對象是XML文件,返回View對象。
LayoutInflater對象的獲取方法
- 調用調用Activity對象的getLayoutInflater()
LayoutInflater inflater = getLayoutInflater();
- 通過Context的實例獲取
LayoutInflater inflater = LayoutInflater.from(context);
- 還是通過Context的實例獲取
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
上面獲取LayoutInflater實例的方法實際上殊途同歸,都是通過調用Context
的getSystemService
方法去獲取的。
先看第二種方法的實現的源碼:
public static LayoutInflater from(Context context) {LayoutInflater LayoutInflater =(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);if (LayoutInflater == null) {throw new AssertionError("LayoutInflater not found.");}return LayoutInflater;}
復制代碼
通過源碼可以看出,第二種方法最終還是通過第三種方法實現的。
Activity 的 getLayoutInflater() 方法是調用 PhoneWindow 的getLayoutInflater()方法,源碼如下:
public PhoneWindow(Context context) {super(context);mLayoutInflater = LayoutInflater.from(context);}public LayoutInflater getLayoutInflater() {return mLayoutInflater;}
復制代碼
所以可以看出,上述三種方式最終本質是都是調用的Context
實例的getSystemService()
。
inflate()方法
通過 sdk 的 api 文檔,可以知道該方法有以下幾種過載形式,返回值均是 View 對象:
public View inflate (int resource, ViewGroup root)
resource:View的layout的ID
root:如果為null,則將此View作為一個獨立的View存在
如果!null, 那么該View會被直接addView進父View,然后將父View返回。public View inflate (XmlPullParser parser, ViewGroup root)
parser:你需要解析xml的解析接口
root:如果為null,則將此View作為一個獨立的View存在
那么該View會被直接addView進父View,然后將父View返回。public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)
parser:你需要解析View的xml的解析接口。
如果root為Null,attachToRoot參數無效,而解析出的View作為一個獨立的View存在。
如果 root不為Null,attachToRoot設為true,那么該View會被直接addView進父View,然后將父View返回。
如果root不為Null,attachToRoot為false,那么會給該View設置一個父View的約束(LayoutParams),然后將其返回。
當root不為null的話,attactToRoot的默認值是true。public View inflate (int resource, ViewGroup root, boolean attachToRoot)
resource:View的layout的ID
如果root為Null,attachToRoot參數無效,而解析出的View作為一個獨立的View存在。
如果 root不為Null,attachToRoot設為true,那么該View會被直接addView進父View,然后將父View返回。
如果root不為Null,attachToRoot為false,那么會給該View設置一個父View的約束(LayoutParams),然后將其返回。
當root不為null的話,attactToRoot的默認值是true。