Android LayoutInflater.inflate源碼分析
LayoutInflater.inflate源碼詳解
LayoutInflater的inflate方法相信大家都不陌生,在Fragment的onCreateView中或者在BaseAdapter的getView方法中我們都會(huì)經(jīng)常用這個(gè)方法來實(shí)例化出我們需要的View.
假設(shè)我們有一個(gè)需要實(shí)例化的布局文件menu_item.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/id_menu_title_tv"
android:layout_width="match_parent"
android:layout_height="300dp"
android:gravity="center_vertical"
android:textColor="@android:color/black"
android:textSize="16sp"
android:text="@string/menu_item"/>
</LinearLayout>
我們想在BaseAdapter的getView()方法中對(duì)其進(jìn)行實(shí)例化,其實(shí)例化的方法有三種,分別是:
2個(gè)參數(shù)的方法:
convertView = mInflater.inflate(R.layout.menu_item, null);
3個(gè)參數(shù)的方法(attachToRoot=false):
convertView = mInflater.inflate(R.layout.menu_item, parent, false);
3個(gè)參數(shù)的方法(attachToRoot=true):
convertView = mInflater.inflate(R.layout.menu_item, parent, true);
究竟我們應(yīng)該用哪個(gè)方法進(jìn)行實(shí)例化View,這3個(gè)方法又有什么區(qū)別呢?如果有同學(xué)對(duì)三個(gè)方法的區(qū)別還不是特別清楚,那么就和我一起從源碼的角度來分析一下這個(gè)問題吧.
源碼
inflate
我們先來看一下兩個(gè)參數(shù)的inflate方法,源碼如下:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
從代碼我們看出,其實(shí)兩個(gè)參數(shù)的inflate方法根據(jù)父布局parent是否為null作為第三個(gè)參數(shù)來調(diào)用三個(gè)參數(shù)的inflate方法,三個(gè)參數(shù)的inflate方法源碼如下:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
// 獲取當(dāng)前應(yīng)用的資源集合
final Resources res = getContext().getResources();
// 獲取指定資源的xml解析器
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
// 返回View之前關(guān)閉parser資源
parser.close();
}
}
這里需要解釋一下,我們傳入的資源布局id是無法直接實(shí)例化的,需要借助XmlResourceParser.
而XmlResourceParser是借助Android的pull解析方法是解析布局文件的.繼續(xù)跟蹤inflate方法源碼:
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
// 獲取上下文對(duì)象,即LayoutInflater.from傳入的Context.
final Context inflaterContext = mContext;
// 根據(jù)parser構(gòu)建XmlPullAttributes.
final AttributeSet attrs = Xml.asAttributeSet(parser);
// 保存之前的Context對(duì)象.
Context lastContext = (Context) mConstructorArgs[0];
// 賦值為傳入的Context對(duì)象.
mConstructorArgs[0] = inflaterContext;
// 注意,默認(rèn)返回的是父布局root.
View result = root;
try {
// 查找xml的開始標(biāo)簽.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
// 如果沒有找到有效的開始標(biāo)簽,則拋出InflateException異常.
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
// 獲取控件名稱.
final String name = parser.getName();
// 特殊處理merge標(biāo)簽
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// 實(shí)例化我們傳入的資源布局的view
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
// 如果傳入的parent不為空.
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// 創(chuàng)建父類型的LayoutParams參數(shù).
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// 如果實(shí)例化的View不需要添加到父布局上,則直接將根據(jù)父布局生成的params參數(shù)設(shè)置
// 給它即可.
temp.setLayoutParams(params);
}
}
// 遞歸的創(chuàng)建當(dāng)前布局的所有控件
rInflateChildren(parser, temp, attrs, true);
// 如果傳入的父布局不為null,且attachToRoot為true,則將實(shí)例化的View加入到父布局root中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果父布局為null或者attachToRoot為false,則將返回值設(shè)置成我們實(shí)例化的View
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (Exception e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}
上述代碼中的關(guān)鍵部分我已經(jīng)加入了中文注釋.從上述代碼中我們還可以發(fā)現(xiàn),我們傳入的布局文件是通過createViewFromTag來實(shí)例化每一個(gè)子節(jié)點(diǎn)的.
createViewFromTag
函數(shù)源碼如下:
/**
* 方便調(diào)用5個(gè)參數(shù)的方法,ignoreThemeAttr的值為false.
*/
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
return createViewFromTag(parent, name, context, attrs, false);
}
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
// 特殊處理“1995”這個(gè)標(biāo)簽(ps: 平時(shí)我們寫xml布局文件時(shí)基本沒有使用過).
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
}
}
在createViewFromTag方法中,最終是通過createView方法利用反射來實(shí)例化view控件的.
createView
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
// 以View的name為key, 查詢構(gòu)造函數(shù)的緩存map中是否已經(jīng)存在該View的構(gòu)造函數(shù).
Constructor<? extends View> constructor = sConstructorMap.get(name);
Class<? extends View> clazz = null;
try {
// 構(gòu)造函數(shù)在緩存中未命中
if (constructor == null) {
// 通過類名去加載控件的字節(jié)碼
clazz = mContext.getClassLoader().loadClass(prefix != null ? (prefix + name) : name).asSubClass(View.class);
// 如果有自定義的過濾器并且加載到字節(jié)碼,則通過過濾器判斷是否允許加載該View
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
// 得到構(gòu)造函數(shù)
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
// 緩存構(gòu)造函數(shù)
sConstructorMap.put(name, constructor);
} else {
if (mFilter != null) {
// 過濾的map是否包含了此類名
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// 重新加載類的字節(jié)碼
clazz = mContext.getClassLoader().loadClass(prefix != null ? (prefix + name) : name).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
// 實(shí)例化類的參數(shù)數(shù)組(mConstructorArgs[0]為Context, [1]為View的屬性)
Object[] args = mConstructorArgs;
args[1] = attrs;
// 通過構(gòu)造函數(shù)實(shí)例化View
final View view = constructor.newInstance(args);
if (View instanceof ViewStub) {
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context)args[0]))
}
return view;
} catch (NoSunchMethodException e) {
// ......
} catch (ClassNotFoundException e) {
// ......
} catch (Exception e) {
// ......
} finally {
// ......
}
}
總結(jié)
通過學(xué)習(xí)了inflate函數(shù)源碼,我們?cè)倩剡^頭去看BaseAdapter的那三種方法,我們可以得出的結(jié)論是:
第一種方法使用不夠規(guī)范, 且會(huì)導(dǎo)致實(shí)例化View的LayoutParams屬性失效.(ps: 即layout_width和layout_height等參數(shù)失效, 因?yàn)樵创a中這種情況的LayoutParams為null).
第二種是最正確,也是最標(biāo)準(zhǔn)的寫法.
第三種由于attachToRoot為true,所以返回的View其實(shí)是父布局ListView,這顯然不是我們想要實(shí)例化的View.因此,第三種寫法是錯(cuò)誤的.
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
ReactNative (API)AsyncStorage存儲(chǔ)詳解及實(shí)例
這篇文章主要介紹了ReactNative (API)AsyncStorage存儲(chǔ)詳解及實(shí)例的相關(guān)資料,需要的朋友可以參考下2016-10-10
Android實(shí)現(xiàn)開機(jī)自動(dòng)啟動(dòng)Service或app的方法
這篇文章主要介紹了Android實(shí)現(xiàn)開機(jī)自動(dòng)啟動(dòng)Service或app的方法,結(jié)合實(shí)例形式分析了Android開機(jī)自啟動(dòng)程序的具體步驟與相關(guān)實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-07-07
Moshi?完美解決Gson在kotlin中默認(rèn)值空的問題詳解
這篇文章主要為大家介紹了Moshi?完美解決Gson在kotlin中默認(rèn)值空的問題詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03
淺談Android硬件加速原理與實(shí)現(xiàn)簡(jiǎn)介
這篇文章主要介紹了淺談Android硬件加速原理與實(shí)現(xiàn)簡(jiǎn)介,本文嘗試從底層硬件原理,一直到上層代碼實(shí)現(xiàn),對(duì)硬件加速技術(shù)進(jìn)行簡(jiǎn)單介紹,感興趣的小伙伴們可以參考一下2018-07-07
Android使用RecyclerView實(shí)現(xiàn)今日頭條頻道管理功能
這篇文章主要為大家詳細(xì)介紹了Android使用RecyclerView實(shí)現(xiàn)今日頭條頻道管理功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07
Android斬首行動(dòng)接口預(yù)請(qǐng)求
這篇文章主要為大家介紹了Android斬首行動(dòng)之接口預(yù)請(qǐng)求實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03

