Android LayoutInflater深入分析及應(yīng)用
LayoutInflater解析
前言:
在Android中,如果是初級(jí)玩家,很可能對(duì)LayoutInflater不太熟悉,或許只是在Fragment的onCreateView()中模式化的使用過而已。但如果稍微有些工作經(jīng)驗(yàn)的人就知道,這個(gè)類有多么重要,它是連接布局XMl和Java代碼的橋梁,我們常常疑惑,為什么Android支持在XML書寫布局?
我們想到的必然是Android內(nèi)部幫我們解析xml文件,LayoutInflater就是幫我們做了這個(gè)工作。
首先LayoutInflater是一個(gè)系統(tǒng)服務(wù),這個(gè)我們可以從from方法看出來
/**
* Obtains the LayoutInflater from the given context.
*/
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;
}
通常我們拿到LayoutInflater對(duì)象之后就會(huì)調(diào)用其inflate方法進(jìn)行加載布局,inflate是一個(gè)重載方法
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
可以看到,我們調(diào)用2個(gè)參數(shù)的方法時(shí)候其默認(rèn)是添加到父布局中的(父布局一般不為空)
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
這個(gè)方法中,其實(shí)是使用Resources將資源ID還原為XMlResoourceParser對(duì)象,然后調(diào)用inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot)方法,解析布局的具體步驟都是在這個(gè)方法中實(shí)現(xiàn)
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
View result = root;
try {
// Look for the root node.
//1.循環(huán)尋找根節(jié)點(diǎn),其實(shí)就是節(jié)點(diǎn)指針遍歷的過程
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
//2.得到節(jié)點(diǎn)的名字,用于判斷該節(jié)點(diǎn)
final String name = parser.getName();
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
//3.對(duì)節(jié)點(diǎn)名字進(jìn)行判斷,然后是merge就將其添加到父布局中(依據(jù)Merge的特性必須添加到父布局中)
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, attrs, false, false);
} else {
//4.創(chuàng)建根據(jù)節(jié)點(diǎn)創(chuàng)建View
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, attrs, false);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
//5.根據(jù)attrs生成布局參數(shù)
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
//6.如果View不添加到父布局中,那就給其本身設(shè)置布局參數(shù)
temp.setLayoutParams(params);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp
// 7.將該節(jié)點(diǎn)下的子View全部加載
rInflate(parser, temp, attrs, true, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
//8.如果添加到父布局中,直接addView
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
//9.如果不添加到父布局,那么將自己返回
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (IOException 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;
}
}
重點(diǎn)的步驟我已經(jīng)加上注釋了,核心
1.找到根布局標(biāo)簽
2.創(chuàng)建根節(jié)點(diǎn)對(duì)應(yīng)的View
3.創(chuàng)建其子View
我們從這里面可以看出來,子View的解析其實(shí)都是rInflate方法,如果xml中有根布局,那么就調(diào)用createViewFromTag創(chuàng)建布局中的根View。我們也可以明白merge的原來,因?yàn)樗苯诱{(diào)用rInflate添加到父View中,看到rInflate(parser, root, attrs, false, false)和rInflate(parser, temp, attrs, true, true)第二個(gè)參數(shù)區(qū)別我們就明白了。
接下來我們看下rInflate如何創(chuàng)建多個(gè)布局
void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs,
boolean finishInflate, boolean inheritContext) throws XmlPullParserException,
IOException {
//獲取當(dāng)前解析器指針?biāo)诠?jié)點(diǎn)處于布局層次
final int depth = parser.getDepth();
int type;
//進(jìn)行樹的深度優(yōu)先遍歷(如果一個(gè)節(jié)點(diǎn)有子節(jié)點(diǎn)將會(huì)再次進(jìn)入rInflate,否則繼續(xù)循環(huán))
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
//如果其中有request_focus標(biāo)簽,那就給這個(gè)節(jié)點(diǎn)View設(shè)置焦點(diǎn)
if (TAG_REQUEST_FOCUS.equals(name)) {
parseRequestFocus(parser, parent);
//如果其中有tag標(biāo)簽,那就給這個(gè)節(jié)點(diǎn)View設(shè)置tag(key,value)
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
//如果其中是include標(biāo)簽,如果include標(biāo)簽
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, parent, attrs, inheritContext);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
//創(chuàng)建該節(jié)點(diǎn)代表的View并添加到父view中,此外遍歷子節(jié)點(diǎn)
final View view = createViewFromTag(parent, name, attrs, inheritContext);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs, true, true);
viewGroup.addView(view, params);
}
}
//代表著一個(gè)節(jié)點(diǎn)含其子節(jié)點(diǎn)遍歷結(jié)束
if (finishInflate) parent.onFinishInflate();
}
從上面可以看到,所以創(chuàng)建View都將會(huì)交給createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext)中,我們可以看下該方法如何創(chuàng)建View
View createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
Context viewContext;
if (parent != null && inheritContext) {
viewContext = parent.getContext();
} else {
viewContext = mContext;
}
// Apply a theme wrapper, if requested.
final TypedArray ta = viewContext.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
viewContext = new ContextThemeWrapper(viewContext, themeResId);
}
ta.recycle();
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(viewContext, attrs);
}
if (DEBUG) System.out.println("******** Creating view: " + name);
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, viewContext, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, viewContext, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, viewContext, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = viewContext;
try {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
if (DEBUG) System.out.println("Created view is: " + view);
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name);
ie.initCause(e);
throw ie;
}
}
其實(shí)很簡單,就是4個(gè)降級(jí)處理
if(factory2!=null){
factory2.onCreateView();
}else if(factory!=null){
factory.onCreateView();
}else if(mPrivateFactory!=null){
mPrivateFactory.onCreateView();
}else{
onCreateView()
}
其他的onCreateView我們不去設(shè)置的話為null,我們看下自己的onCreateView(),其實(shí)這個(gè)方法會(huì)調(diào)用createView()
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
//從構(gòu)造器Map(緩存)中獲取需要的構(gòu)造器
Constructor<? extends View> constructor = sConstructorMap.get(name);
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
//如果緩存中沒有需要的構(gòu)造器,那就通過ClassLoader加載需要的類
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
//將使用過的構(gòu)造器緩存
constructor = clazz.getConstructor(mConstructorSignature);
sConstructorMap.put(name, constructor);
} else {
// If we have a filter, apply it to cached constructor
if (mFilter != null) {
// Have we seen this name before?
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// New class -- remember whether it is allowed
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);
}
}
}
Object[] args = mConstructorArgs;
args[1] = attrs;
constructor.setAccessible(true);
//通過反射獲取需要的實(shí)例對(duì)象
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
//ViewStub將創(chuàng)建一個(gè)屬于自己的LayoutInflater,因?yàn)樗枰诓煌臅r(shí)機(jī)去inflate
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
return view;
} catch (NoSuchMethodException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
} catch (ClassCastException e) {
// If loaded class is not a View subclass
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Class is not a View "
+ (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
} catch (ClassNotFoundException e) {
// If loadClass fails, we should propagate the exception.
throw e;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (clazz == null ? "<unknown>" : clazz.getName()));
ie.initCause(e);
throw ie;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
大體步驟就是,
1.從緩存中獲取特定View構(gòu)造器,如果沒有,則加載對(duì)應(yīng)的類,并緩存該構(gòu)造器,
2.利用構(gòu)造器反射構(gòu)造對(duì)應(yīng)的View
3.如果是ViewStub則復(fù)制一個(gè)LayoutInflater對(duì)象傳遞給它
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
Android開發(fā)之BottomSheetDialog組件的使用
BottomSheetDialog是底部操作控件,可在屏幕底部創(chuàng)建一個(gè)支持滑動(dòng)關(guān)閉視圖。本文將通過示例詳細(xì)講解它的使用,感興趣的小伙伴可以了解一下2023-01-01
Android編程之canvas繪制各種圖形(點(diǎn),直線,弧,圓,橢圓,文字,矩形,多邊形,曲線,圓角矩形)
這篇文章主要介紹了Android編程之canvas繪制各種圖形的方法,涉及Android使用Canvas類中常用繪圖方法的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-12-12
android實(shí)現(xiàn)獲取正在運(yùn)行的應(yīng)用程序
android如何獲取正在運(yùn)行的應(yīng)用程序,因?yàn)樵趂ramework中想添加這個(gè)功能,所以寫了個(gè)appliction來實(shí)現(xiàn)一下獲取正在運(yùn)行的應(yīng)用程序2013-01-01
android教程使用webview訪問https的url處理sslerror示例
這篇文章主要介紹了android教程使用webview訪問https的url處理sslerror示例,大家參考使用吧2014-01-01
Kotlin中ListView與RecyclerView的應(yīng)用講解
這篇文章主要介紹了Kotlin中ListView與RecyclerView的應(yīng)用講解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-09-09
Android持久化技術(shù)之SharedPreferences存儲(chǔ)實(shí)例詳解
這篇文章主要介紹了Android持久化技術(shù)之SharedPreferences存儲(chǔ),結(jié)合實(shí)例形式較為詳細(xì)的分析了SharedPreferences存儲(chǔ)的原理、應(yīng)用及具體實(shí)現(xiàn)方法,需要的朋友可以參考下2016-01-01
Android 動(dòng)畫實(shí)現(xiàn)幾種方案
這篇文章主要介紹了Android 動(dòng)畫實(shí)現(xiàn)幾種方案的相關(guān)資料,需要的朋友可以參考下2017-06-06

