寫作背景
在Android源碼實(shí)現(xiàn)部分,很多人都應(yīng)該分析過(guò)View的繪制流程,measure,layout,draw三個(gè)過(guò)程也許已經(jīng)十分熟悉了,但是相信有很多小伙伴和筆者一樣并不知道到xml布局到底是如何被解析然后轉(zhuǎn)換成View的,今天筆者將和大家一起來(lái)學(xué)習(xí)這個(gè)流程(基于Android API 28源碼)。
View加載的調(diào)用
在Android開(kāi)發(fā)過(guò)程中,使用XML文件編寫UI界面后,通常我們會(huì)調(diào)用setContentView(resId)或者LayoutInflater.inflate(resId,...)的方式把布局文件加載到Activity中,并實(shí)現(xiàn)視圖與邏輯的綁定與開(kāi)發(fā)。
Activity的setContentView
setContentView方法大家都已經(jīng)非常熟悉了,無(wú)論是系統(tǒng)原生的Activity還是V7或V4包下的其他子類Activity,在onCreate方法中一般都會(huì)調(diào)用到這個(gè)方法,下面來(lái)看看源碼:
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
public Window getWindow() {
return mWindow;
}
由于之前已經(jīng)分析過(guò)Window,所以這里就不再贅述,我們關(guān)注本文的重點(diǎn)部分setContentView,在Activity的setContentView方法里傳遞給了PhoneWindow的setContentView方法來(lái)執(zhí)行布局的加載。
getWindow()方法返回的是一個(gè)Window對(duì)象,具體是其實(shí)現(xiàn)類PhoneWindow對(duì)象,對(duì)應(yīng)的是mWindow字段。這里簡(jiǎn)單提一下,不清楚的可以看筆者的這篇文章
現(xiàn)在繼續(xù)關(guān)注PhoneWindow的setContentView源碼:
@Override
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
// 將View添加到DecorView的mContentParent中
// 調(diào)用LayoutInflater的inflate方法解析布局文件,并生成View樹(shù),mContentParent為View樹(shù)的根節(jié)點(diǎn)
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
//回調(diào)Activity的onContentChanged方法通知視圖發(fā)生改變
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
這里也比較清楚,當(dāng)我們沒(méi)有設(shè)置轉(zhuǎn)場(chǎng)動(dòng)畫的會(huì)執(zhí)行mLayoutInflater.inflate(layoutResID, mContentParent),而這個(gè)mLayoutInflater是在PhoneWindow的構(gòu)造方法中被實(shí)例的:
public PhoneWindow(Context context) {
super(context);
mLayoutInflater = LayoutInflater.from(context);
}
所以我們可以得出結(jié)論Activity的setContentView方法最終就是通過(guò) LayoutInflater.from(context).inflate(resId, ……) 來(lái)實(shí)現(xiàn)布局的解析然后加載出來(lái)的.而其他子類Activity雖然可能復(fù)寫了setContentView方法,但還是可以發(fā)現(xiàn)其最終的實(shí)現(xiàn)方式是一樣的,這里看一下v7包下的AppCompatActivty的setContentView方法:
@Override
public void setContentView(@LayoutRes int layoutResID) {
getDelegate().setContentView(layoutResID);
}
//android.support.v7.app.AppCompatDelegateImplV9.setContentView(resId)
@Override
public void setContentView(int resId) {
ensureSubDecor();
ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
contentParent.removeAllViews();
LayoutInflater.from(mContext).inflate(resId, contentParent);
mOriginalWindowCallback.onContentChanged();
}
果然不出意外,這里又出現(xiàn)了了LayoutInflater的身影。所以進(jìn)一步得出結(jié)論:xml文件是用LayoutInflater的inflate方法來(lái)實(shí)現(xiàn)解析與加載的。
LayoutInflater如何實(shí)例化
看一下源碼中的LayoutInflater是怎樣介紹的:
/**
* Instantiates a layout XML file into its corresponding {@link android.view.View}
* objects. It is never used directly. Instead, use
* {@link android.app.Activity#getLayoutInflater()} or
* {@link Context#getSystemService} to retrieve a standard LayoutInflater instance
* that is already hooked up to the current context and correctly configured
* for the device you are running on.
*
* <p>
* To create a new LayoutInflater with an additional {@link Factory} for your
* own views, you can use {@link #cloneInContext} to clone an existing
* ViewFactory, and then call {@link #setFactory} on it to include your
* Factory.
*
* <p>
* For performance reasons, view inflation relies heavily on pre-processing of
* XML files that is done at build time. Therefore, it is not currently possible
* to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
* it only works with an XmlPullParser returned from a compiled resource
* (R.<em>something</em> file.)
*/
@SystemService(Context.LAYOUT_INFLATER_SERVICE)
public abstract class LayoutInflater {···}
從注釋的第一行我們也可以發(fā)現(xiàn)LayoutInflater是用來(lái)實(shí)例化一個(gè)XML
文件到對(duì)應(yīng)的View對(duì)象的一個(gè)類,并且并不希望被直接使用,而是通過(guò)Activity的getLayoutInflater()方法或者Context的getSystemService()來(lái)或取一個(gè)標(biāo)準(zhǔn)的LayoutInflater對(duì)象。在類上面的注釋我們也可以發(fā)現(xiàn)使用Context.LAYOUT_INFLATER_SERVICE通過(guò)getSystemService方法來(lái)獲取。最后再看這個(gè)類,發(fā)現(xiàn)是一個(gè)抽象類,抽象類是不能夠被實(shí)例化的,所以這也就會(huì)出現(xiàn)注釋中所寫的兩種方法來(lái)獲取實(shí)例了:
Activity的getLayoutInflater
public LayoutInflater getLayoutInflater() {
return getWindow().getLayoutInflater();
}
這里就可以發(fā)現(xiàn)Activity獲取LayoutInflater是通過(guò)PhoneWindow的getLayutInflater方法來(lái)獲取的,最終的到的對(duì)象就是PhoneWindow中的mLayoutInflater;而這個(gè)mLayoutInflater上文也介紹過(guò),是通過(guò)LayoutInflater.from(context)方法來(lái)創(chuàng)建的:
/**
* 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,然后在看代碼的具體實(shí)現(xiàn)。看過(guò)這段代碼相信大家已經(jīng)有了答案。沒(méi)錯(cuò),事實(shí)的真相只有一個(gè),那就是通過(guò)服務(wù)獲取LayoutInflater實(shí)例對(duì)象。那么現(xiàn)在該繼續(xù)深入context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)方法的具體實(shí)現(xiàn)了:
由于Context的實(shí)現(xiàn)類是ContextImpl,所以實(shí)際調(diào)用的是它的方法:
@Override
public Object getSystemService(String name) {
return SystemServiceRegistry.getSystemService(this, name);
}
//SystemServiceRegistry.class
/**
* Gets a system service from a given context.
*/
public static Object getSystemService(ContextImpl ctx, String name) {
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
在ContextImpl的getSystemService方法中調(diào)用了SystemServiceRegistry的getSystemService方法,根據(jù)這個(gè)類的命名可以猜測(cè)這是一個(gè)提供系統(tǒng)服務(wù)注冊(cè)的類,在這個(gè)類的代碼中我們發(fā)現(xiàn)非常多的服務(wù)的注冊(cè)工作,就像這樣:
static {
registerService(Context.ACCESSIBILITY_SERVICE, AccessibilityManager.class,
new CachedServiceFetcher<AccessibilityManager>() {
@Override
public AccessibilityManager createService(ContextImpl ctx) {
return AccessibilityManager.getInstance(ctx);
}});
registerService(Context.CAPTIONING_SERVICE, CaptioningManager.class,
new CachedServiceFetcher<CaptioningManager>() {
@Override
public CaptioningManager createService(ContextImpl ctx) {
return new CaptioningManager(ctx);
}});
···
}
/**
* Statically registers a system service with the context.
* This method must be called during static initialization only.
*/
private static <T> void registerService(String serviceName, Class<T> serviceClass,
ServiceFetcher<T> serviceFetcher) {
SYSTEM_SERVICE_NAMES.put(serviceClass, serviceName);
SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
}
這里有大量的服務(wù)注冊(cè)工作,所以省略了大量代碼,現(xiàn)在來(lái)看看要通過(guò)Context.LAYOUT_INFLATER_SERVICE獲取的服務(wù)是如何被注冊(cè)的:
···
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher<LayoutInflater>() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
return new PhoneLayoutInflater(ctx.getOuterContext());
}});
···
顯然我們想要獲取的服務(wù)就是這里提前注冊(cè)過(guò)的服務(wù),也就是一個(gè)PhoneLayoutInflater對(duì)象,之前就說(shuō)過(guò)LayoutInflater是一個(gè)抽象類,現(xiàn)在終于找到了它的實(shí)現(xiàn)類了。
LayoutInflater讀取xml文件并創(chuàng)建View
通過(guò)LayoutInflater.from(context)獲取到了LayoutInflater實(shí)例后,現(xiàn)在要調(diào)用它的inflate方法來(lái)實(shí)現(xiàn)xml文件的讀取與View的創(chuàng)建:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root) {
return inflate(parser, root, root != null);
}
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) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
可以看到這里有三個(gè)inflate的重載方法,但是比較重要的就是后一個(gè),主要是通過(guò)Resourse對(duì)象通過(guò)getLayout方法將resId轉(zhuǎn)換成一個(gè)XmlResourceParser對(duì)象,然后又調(diào)用了一個(gè)inflate方法:
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
```
final String name = parser.getName();
···
//第一部分merge標(biāo)簽
//內(nèi)部靜態(tài)常量private static final String TAG_MERGE = "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, inflaterContext, attrs, false);
//另一部分
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
···
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
···
// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);
···
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
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.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
···
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
這一個(gè)inflater方法也就是最重要的inflater方法了,首先遍歷XmlPullParser對(duì)象,尋找根節(jié)點(diǎn),并賦值給type。找到根節(jié)點(diǎn)后的實(shí)現(xiàn)比較長(zhǎng),這里分成了兩個(gè)部分來(lái)講,分別是merge部分和其他view部分。
merge標(biāo)簽
首先根據(jù)標(biāo)簽名判斷是否是merge標(biāo)簽,如果是merge標(biāo)簽則根節(jié)點(diǎn)不能為null并且attachToRoot必須為true,否則拋出異常,這很容易理解因?yàn)槭褂胢erge標(biāo)簽的xml布局需要依附在一個(gè)父布局之下,然后會(huì)調(diào)用rInflater方法:
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
//獲取View樹(shù)的深度 深度優(yōu)先遍歷
final int depth = parser.getDepth();
int type;
boolean pendingRequestFocus = false;
//依次解析
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();
// 內(nèi)部定義的靜態(tài)常量:
//private static final String TAG_REQUEST_FOCUS = "requestFocus";
if (TAG_REQUEST_FOCUS.equals(name)) {
pendingRequestFocus = true;
consumeChildElements(parser);
// private static final String TAG_TAG = "tag";
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
// 解析include標(biāo)簽
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
//如果是merge標(biāo)簽 拋出異常 因?yàn)閙erge標(biāo)簽必須為根視圖
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
//遞歸調(diào)用解析 深度優(yōu)先遍歷
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (pendingRequestFocus) {
parent.restoreDefaultFocus();
}
if (finishInflate) {
parent.onFinishInflate();
}
}
首先會(huì)遍歷整個(gè)節(jié)點(diǎn),子節(jié)點(diǎn)會(huì)有"requestFocus"、"tag"、""、"include",但是不能有"merge",因?yàn)閙erge標(biāo)簽只能為這里的根元素,除此之外的View標(biāo)簽會(huì)通過(guò)createViewFromTag方法創(chuàng)建View,實(shí)際上"include"標(biāo)簽也會(huì)創(chuàng)建view,我們看parseInclude方法:
private void parseInclude(XmlPullParser parser, Context context, View parent,
AttributeSet attrs) throws XmlPullParserException, IOException {
int type;
if (parent instanceof ViewGroup) {
// Apply a theme wrapper, if requested. This is sort of a weird
// edge case, since developers think the <include> overwrites
// values in the AttributeSet of the included View. So, if the
// included View has a theme attribute, we'll need to ignore it.
//private static final int[] ATTRS_THEME = new int[] {
com.android.internal.R.attr.theme };
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
final boolean hasThemeOverride = themeResId != 0;
if (hasThemeOverride) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
// If the layout is pointing to a theme attribute, we have to
// massage the value to get a resource identifier out of it.
int layout = attrs.getAttributeResourceValue(null, ATTR_LAYOUT, 0);
if (layout == 0) {
final String value = attrs.getAttributeValue(null, ATTR_LAYOUT);
if (value == null || value.length() <= 0) {
throw new InflateException("You must specify a layout in the"
+ " include tag: <include layout=\"@layout/layoutID\" />");
}
// Attempt to resolve the "?attr/name" string to an attribute
// within the default (e.g. application) package.
layout = context.getResources().getIdentifier(
value.substring(1), "attr", context.getPackageName());
}
// The layout might be referencing a theme attribute.
if (mTempValue == null) {
mTempValue = new TypedValue();
}
if (layout != 0 && context.getTheme().resolveAttribute(layout, mTempValue, true)) {
layout = mTempValue.resourceId;
}
if (layout == 0) {
final String value = attrs.getAttributeValue(null, ATTR_LAYOUT);
throw new InflateException("You must specify a valid layout "
+ "reference. The layout ID " + value + " is not valid.");
} else {
final XmlResourceParser childParser = context.getResources().getLayout(layout);
try {
final AttributeSet childAttrs = Xml.asAttributeSet(childParser);
while ((type = childParser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty.
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(childParser.getPositionDescription() +
": No start tag found!");
}
final String childName = childParser.getName();
if (TAG_MERGE.equals(childName)) {
// The <merge> tag doesn't support android:theme, so
// nothing special to do here.
rInflate(childParser, parent, context, childAttrs, false);
} else {
final View view = createViewFromTag(parent, childName,
context, childAttrs, hasThemeOverride);
final ViewGroup group = (ViewGroup) parent;
final TypedArray a = context.obtainStyledAttributes(
attrs, R.styleable.Include);
final int id = a.getResourceId(R.styleable.Include_id, View.NO_ID);
final int visibility = a.getInt(R.styleable.Include_visibility, -1);
a.recycle();
// We try to load the layout params set in the <include /> tag.
// If the parent can't generate layout params (ex. missing width
// or height for the framework ViewGroups, though this is not
// necessarily true of all ViewGroups) then we expect it to throw
// a runtime exception.
// We catch this exception and set localParams accordingly: true
// means we successfully loaded layout params from the <include>
// tag, false means we need to rely on the included layout params.
ViewGroup.LayoutParams params = null;
try {
params = group.generateLayoutParams(attrs);
} catch (RuntimeException e) {
// Ignore, just fail over to child attrs.
}
if (params == null) {
params = group.generateLayoutParams(childAttrs);
}
view.setLayoutParams(params);
// Inflate all children.
rInflateChildren(childParser, view, childAttrs, true);
if (id != View.NO_ID) {
view.setId(id);
}
switch (visibility) {
case 0:
view.setVisibility(View.VISIBLE);
break;
case 1:
view.setVisibility(View.INVISIBLE);
break;
case 2:
view.setVisibility(View.GONE);
break;
}
group.addView(view);
}
} finally {
childParser.close();
}
}
} else {
throw new InflateException("<include /> can only be used inside of a ViewGroup");
}
LayoutInflater.consumeChildElements(parser);
}
這個(gè)方法跟上面的inflate()方法很相似,具體邏輯就不看了,主要也是調(diào)用了createViewFromTag()方法來(lái)創(chuàng)建View,這就是上面為什么說(shuō)include標(biāo)簽也會(huì)創(chuàng)建view的原因,至此我們已經(jīng)知道了createViewFromTag方法用于創(chuàng)建View。
其他View標(biāo)簽
上面我們看完了inflate里的merge標(biāo)簽實(shí)現(xiàn),現(xiàn)在繼續(xù)看看后面的實(shí)現(xiàn):
···
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
···
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);
}
}
···
// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);
···
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
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.
if (root == null || !attachToRoot) {
result = temp;
}
···
首先這里還是調(diào)用了createViewFromTag方法用于創(chuàng)建view,然后當(dāng)根View不為空時(shí),則加載根View的LayoutParams屬性,然后如果attachToRoot為false,則調(diào)用setLayoutParams為創(chuàng)建的View設(shè)置屬性,如果為true則直接調(diào)用addView方法添加到根View中。然后會(huì)調(diào)用rInflateChildren方法來(lái)實(shí)現(xiàn)子view的創(chuàng)建與添加。最后如果根View不為空并且attachToRoot為true,則返回根View,否則返回的是創(chuàng)建的xml根標(biāo)簽指定的View。
createViewFromTag創(chuàng)建View
現(xiàn)在知道了createViewFromTag用于創(chuàng)建View,那么現(xiàn)在需要了解一下它的實(shí)現(xiàn)細(xì)節(jié):
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) {
···
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);
}
//注釋1
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;
}
···
}
這里首先會(huì)使用mFactory2,mFactory,mPrivateFactory這三個(gè)對(duì)象按先后順序創(chuàng)建view,但那如果這三個(gè)對(duì)象都為空的話,則會(huì)默認(rèn)流程來(lái)創(chuàng)建View,最后返回View。通常來(lái)講這三個(gè)Factory都為空,如果我們想要控制View的創(chuàng)建過(guò)程就可以利用這一機(jī)制來(lái)定制自己的factory。現(xiàn)在我們先來(lái)分析一下注釋1的代碼:
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
//String的indexOf()方法如果沒(méi)有找到給定的字符則返回-1
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
首先會(huì)判斷名字中是否含有點(diǎn),這主要是為了區(qū)分系統(tǒng)自帶View和自定義View。因?yàn)橄到y(tǒng)View是直接使用類名不用寫全包名的,而自定義View在使用的時(shí)候一定要寫全包名,相信大家可以很容易的理解到這一點(diǎn),然后如果是自定義View則調(diào)用createView來(lái)創(chuàng)建View,否則調(diào)用onCreateView方法。
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(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
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);
}
}
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;
//注釋1
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;
} catch (NoSuchMethodException e) {
···
} finally {
···
}
}
LayoutInflater內(nèi)部維護(hù)了一個(gè)Map用于緩存構(gòu)造器,然后在這里首先會(huì)從這個(gè)map中獲取構(gòu)造器否則創(chuàng)建后再放至map中;當(dāng)獲取了構(gòu)造器之后,在注釋1處通過(guò)反射創(chuàng)建了View。然后我們?cè)倏磩?chuàng)建系統(tǒng)View:
在LayoutInflater中我們找到了對(duì)應(yīng)的方法:
protected View onCreateView(View parent, String name, AttributeSet attrs)
throws ClassNotFoundException {
return onCreateView(name, attrs);
}
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
原來(lái)在LayoutInflater的onCreateView方法創(chuàng)建系統(tǒng)View最終的實(shí)現(xiàn)也是交給了createView方法,只是傳入了一個(gè)字符串android.view.,這樣在創(chuàng)建構(gòu)造器時(shí)就會(huì)與View的名字拼接到一起獲取對(duì)應(yīng)的Class對(duì)象,使最終能夠成功創(chuàng)建對(duì)應(yīng)的View。現(xiàn)在到PhoneLayoutInflater里找一下這個(gè)方法:
private static final String[] sClassPrefixList = {
"android.widget.",
"android.webkit.",
"android.app."
};
/** Override onCreateView to instantiate names that correspond to the
widgets known to the Widget factory. If we don't find a match,
call through to our super class.
*/
@Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
for (String prefix : sClassPrefixList) {
try {
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);
}
主要完成的是遍歷一個(gè)存放了三個(gè)包名字符串的數(shù)組,然后調(diào)用createView方法創(chuàng)建View,只要這三次創(chuàng)建View有一次成功,那么就返回創(chuàng)建的View,否則最終返回的還是父類傳入"android.view."時(shí)創(chuàng)建的View。現(xiàn)在再看看createView的具體實(shí)現(xiàn):
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;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
//沒(méi)有緩存的構(gòu)造器
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
//通過(guò)傳入的prefix構(gòu)造出完整的類名 并加載該類
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
//省略部分代碼
//從class對(duì)象中獲取構(gòu)造器
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
//存入緩存器中
sConstructorMap.put(name, constructor);
} else {
//代碼省略
}
//代碼省略
//通過(guò)反射創(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代碼
}
這里就創(chuàng)建了View對(duì)象,結(jié)合之前調(diào)用的rInflate方法構(gòu)建整個(gè)View樹(shù),整個(gè)View樹(shù)上的對(duì)象就全部被創(chuàng)建出來(lái)了,最后就會(huì)被調(diào)用顯示在我們的視野中。