本文主要介紹android中布局填充器的實(shí)現(xiàn)详恼,即把Xml布局文件解析成View的過(guò)程浑塞。以下源碼摘自android8.0
目錄
- LayoutInflater.from()
- inflate()
- 總結(jié)
一郑叠、LayoutInflater.from()
該方法最終會(huì)拿到一個(gè)PhoneLayoutInflater實(shí)例膏燕,它繼承了LayoutInflater抽象類
1. 源碼分析
LayoutInflater抽象類
public static LayoutInflater from(Context context) {
//假設(shè)傳入的是Activity第焰,Activity啟動(dòng)后初始化的上下文就是ContextImpl,Activity的啟動(dòng)過(guò)程
//這里不再闡述讹开,其實(shí)是調(diào)ContextImpl的getSystemService
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
ContextImpl類
public Object getSystemService(String name) {
//直接調(diào)SystemServiceRegistry的getSystemService方法
return SystemServiceRegistry.getSystemService(this, name);
}
SystemServiceRegistry類
public static Object getSystemService(ContextImpl ctx, String name) {
//SYSTEM_SERVICE_FETCHERS是個(gè)HashMap,ServiceFetcher<T>是個(gè)接口捐名,里邊只有一個(gè)getService接口方法
//這個(gè)name就是LAYOUT_INFLATER_SERVICE旦万,因此我們看它是什么時(shí)候往HashMap中添加的,我們會(huì)發(fā)現(xiàn)在該類中
//會(huì)有個(gè)靜態(tài)代碼塊
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
static{
...
//該方法會(huì)向HashMap中添加服務(wù)
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher<LayoutInflater>() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
//從這里可以看到我們獲取到的其實(shí)是PhoneLayoutInflater實(shí)例
return new PhoneLayoutInflater(ctx.getOuterContext());
}
});
...
}
private static <T> void registerService(String serviceName, Class<T> serviceClass,
ServiceFetcher<T> serviceFetcher) {
SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
//HashMap中添加服務(wù)
SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
}
2. 調(diào)用過(guò)程
二镶蹋、inflate()
由上可知成艘,其實(shí)我們獲取到的其實(shí)是PhoneLayoutInflater實(shí)例,而PhoneLayoutInflater繼承了LayoutInflater抽象類贺归,其實(shí)調(diào)的是LayoutInflater中的inflate方法淆两,我們假設(shè)調(diào)用的是inflate(R.layout.activity_main, null)方法
1. 源碼分析
LayoutInflater抽象類
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
//調(diào)另一個(gè)重載的方法
return inflate(resource, root, root != null);
}
//第一個(gè)參數(shù)為布局文件id,第二參數(shù)個(gè)為null拂酣,第三個(gè)參數(shù)為false
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
//獲取xml解析器秋冰,interface XmlResourceParser extends XmlPullParser
final XmlResourceParser parser = res.getLayout(resource);
try {
//調(diào)另一個(gè)重載的inflate方法
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
...
View result = root;
// Look for the root node.
int type;
//找到第一個(gè)開(kāi)始標(biāo)簽
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!");
}
//獲取標(biāo)簽名
final String name = parser.getName();
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");
}
//如果第一個(gè)標(biāo)簽是merge,那就調(diào)用rInflate解析
rInflate(parser, root, inflaterContext, attrs, false);
} else {
//第一個(gè)標(biāo)簽不是merge婶熬,就調(diào)createViewFromTag剑勾,該方法把一個(gè)標(biāo)簽解析成相應(yīng)的View
//我們假設(shè)第一個(gè)標(biāo)簽是RelativeLayout
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
...
//解析RelativeLayout下面的標(biāo)簽,該方法和merge一樣也會(huì)調(diào)到rInflate方法
rInflateChildren(parser, temp, attrs, true);
...
if (root == null || !attachToRoot) {
//直接把解析的temp返回
result = temp;
}
}
...省略try-catch...
return result;
}
}
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
//直接調(diào)rInflate方法
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
整個(gè)過(guò)程就是先判斷是否是merge標(biāo)簽赵颅,是merge標(biāo)簽就走rInflate方法虽另,不是的話就先走createViewFromTag方法拿到第一個(gè)標(biāo)簽對(duì)象的View,再走rInflate方法饺谬,最后返回一顆View樹(shù)捂刺,因此這里我們只需要關(guān)注createViewFromTag和rInflate這兩個(gè)方法,下面先看createViewFromTag方法是如何把標(biāo)簽解析成對(duì)應(yīng)的View的
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
//直接調(diào)五個(gè)參數(shù)重載的方法
return createViewFromTag(parent, name, context, attrs, false);
}
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
...
if (name.equals(TAG_1995)) {
//TAG_1995是blink字符串募寨,即如果是眨眼標(biāo)簽blink叠萍,
//那就直接返回,BlinkLayout類是LayoutInflater的內(nèi)部類
return new BlinkLayout(context, attrs);
}
View view;
//這些工廠默認(rèn)都是null
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);
}
//開(kāi)始解析
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
//系統(tǒng)控件绪商,沒(méi)有點(diǎn)苛谷,系統(tǒng)控件最終加上android.widget的前綴
//最后也是調(diào)LayoutInFlater的createView方法
view = onCreateView(parent, name, attrs);
} else {
//自定義控件,有點(diǎn)格郁,不用加前綴
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
...省略try-catch...
}
protected View onCreateView(View parent, String name, AttributeSet attrs)
throws ClassNotFoundException {
//由于真正的實(shí)例是PhoneLayoutInflater腹殿,而PhoneLayoutInflater又重寫了
//onCreateView方法独悴,因此這里會(huì)調(diào)PhoneLayoutInflater中的onCreateView
return onCreateView(name, attrs);
}
PhoneLayoutInflater類
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
@Override
protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
for (String prefix : sClassPrefixList) {
try {
//調(diào)LayoutInflater的createView方法
//該方法會(huì)給系統(tǒng)控件加上android.widget.前綴
View view = createView(name, prefix, attrs);
if (view != null) {
return view;
}
} catch (ClassNotFoundException e) {
// In this case we want to let the base class take a crack
// at it.
}
}
return super.onCreateView(name, attrs);
}
不管是自定義控件腾降,還是系統(tǒng)控件最終都會(huì)調(diào)到LayoutInflater的createView方法
LayoutInflater類
//系統(tǒng)控件的前綴為android.widget况褪,自定義控件的前綴是null,即沒(méi)有前綴
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
//從緩存中獲取構(gòu)造
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
//緩存中沒(méi)有就創(chuàng)建一個(gè)栖榨,系統(tǒng)控件會(huì)加上android.widget
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);
}
}
//從Class中獲取構(gòu)造自沧,并加入到緩存中
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
...
}
Object lastContext = mConstructorArgs[0];
if (mConstructorArgs[0] == null) {
// Fill in the context if not already within inflation.
mConstructorArgs[0] = mContext;
}
Object[] args = mConstructorArgs;
args[1] = attrs;
//反射創(chuàng)建View
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
mConstructorArgs[0] = lastContext;
return view;
...省略try-catch...
}
從上面可以看到從標(biāo)簽到響應(yīng)View的過(guò)程是通過(guò)反射來(lái)實(shí)現(xiàn)的坟奥,并且構(gòu)造的獲取使用了享元模式,下面看另一個(gè)rInflate方法
LayoutInflater類
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
boolean pendingRequestFocus = false;
//注意這個(gè)循環(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();
if (TAG_REQUEST_FOCUS.equals(name)) {
pendingRequestFocus = true;
consumeChildElements(parser);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
//解析include
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
//merge標(biāo)簽必須是根標(biāo)簽拇厢,這里不應(yīng)該有merge爱谁,直接拋出異常
throw new InflateException("<merge /> must be the root element");
} else {
//上面已經(jīng)講過(guò)了,該方法會(huì)把單個(gè)標(biāo)簽解析成對(duì)應(yīng)的View
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
//rInflateChildren方法直接會(huì)掉當(dāng)前這個(gè)rInflate方法孝偎,即遞歸解析访敌,并且是深度優(yōu)先
rInflateChildren(parser, view, attrs, true);
//添加到父View上
viewGroup.addView(view, params);
}
}
...
}
2. 調(diào)用過(guò)程
三、總結(jié)
1衣盾、xml布局文件的解析是通過(guò)XmlPullParser寺旺,即android內(nèi)置的pull解析,至于Dom解析势决、Sax解析阻塑、Pull解析的區(qū)別和使用自行百度
2、布局中的每個(gè)標(biāo)簽分為系統(tǒng)控件和自定義控件果复,它們用點(diǎn)來(lái)區(qū)分叮姑,有點(diǎn)就是自定義控件,沒(méi)點(diǎn)就是系統(tǒng)控件据悔,系統(tǒng)控件最終也會(huì)加上android.widget前綴形成完整路徑名
3传透、最終每個(gè)標(biāo)簽都是通過(guò)反射創(chuàng)建拿到相應(yīng)的控件實(shí)例,最終會(huì)通過(guò)深度優(yōu)先的順序解析形成一顆View樹(shù)