Android 中的LayoutInflater的理解
LayoutInflater與findViewById的區(qū)別?
- 對(duì)于一個(gè)已經(jīng)載入的界面,就可以使用findViewById()方法來(lái)獲得其中的界面元素。
- 對(duì)于一個(gè)沒(méi)有被載入或者想要?jiǎng)討B(tài)載入的界面,就需要使用LayoutInflater對(duì)象的inflate()方法來(lái)載入。
- findViewById()是查找已被實(shí)例化為View對(duì)象的xml布局文件下的具體控件(如Button、TextView等),操作對(duì)象是一個(gè)ViewGroup或者是Activity,返回一個(gè)View對(duì)象。
- LayoutInflater實(shí)例的inflate()方法是用來(lái)將res/layout/下的xml布局文件實(shí)例化,操作對(duì)象是XML文件,返回View對(duì)象。
LayoutInflater對(duì)象的獲取方法
LayoutInflater inflater = getLayoutInflater();
LayoutInflater inflater = LayoutInflater.from(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
上面獲取LayoutInflater實(shí)例的方法實(shí)際上殊途同歸,都是通過(guò)調(diào)用Context的getSystemService方法去獲取的。
先看第二種方法的實(shí)現(xiàn)的源碼:
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;} 復(fù)制代碼通過(guò)源碼可以看出,第二種方法最終還是通過(guò)第三種方法實(shí)現(xiàn)的。
Activity 的 getLayoutInflater() 方法是調(diào)用 PhoneWindow 的getLayoutInflater()方法,源碼如下:
public PhoneWindow(Context context) {super(context);mLayoutInflater = LayoutInflater.from(context);}public LayoutInflater getLayoutInflater() {return mLayoutInflater;} 復(fù)制代碼所以可以看出,上述三種方式最終本質(zhì)是都是調(diào)用的Context實(shí)例的getSystemService()。
inflate()方法
通過(guò) sdk 的 api 文檔,可以知道該方法有以下幾種過(guò)載形式,返回值均是 View 對(duì)象:
- public View inflate (int resource, ViewGroup root)
resource:View的layout的ID
root:如果為null,則將此View作為一個(gè)獨(dú)立的View存在
如果!null, 那么該View會(huì)被直接addView進(jìn)父View,然后將父View返回。 - public View inflate (XmlPullParser parser, ViewGroup root)
parser:你需要解析xml的解析接口
root:如果為null,則將此View作為一個(gè)獨(dú)立的View存在
那么該View會(huì)被直接addView進(jìn)父View,然后將父View返回。 - public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot)
parser:你需要解析View的xml的解析接口。
如果root為Null,attachToRoot參數(shù)無(wú)效,而解析出的View作為一個(gè)獨(dú)立的View存在。
如果 root不為Null,attachToRoot設(shè)為true,那么該View會(huì)被直接addView進(jìn)父View,然后將父View返回。
如果root不為Null,attachToRoot為false,那么會(huì)給該View設(shè)置一個(gè)父View的約束(LayoutParams),然后將其返回。
當(dāng)root不為null的話,attactToRoot的默認(rèn)值是true。 - public View inflate (int resource, ViewGroup root, boolean attachToRoot)
resource:View的layout的ID
如果root為Null,attachToRoot參數(shù)無(wú)效,而解析出的View作為一個(gè)獨(dú)立的View存在。
如果 root不為Null,attachToRoot設(shè)為true,那么該View會(huì)被直接addView進(jìn)父View,然后將父View返回。
如果root不為Null,attachToRoot為false,那么會(huì)給該View設(shè)置一個(gè)父View的約束(LayoutParams),然后將其返回。
當(dāng)root不為null的話,attactToRoot的默認(rèn)值是true。
總結(jié)
以上是生活随笔為你收集整理的Android 中的LayoutInflater的理解的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 前端学习(3098):vue+eleme
- 下一篇: Android小程序白屏,微信小程序we