通过上篇的LayoutInflater 分析,我们知道了LayoutInflater服务的注册流程,最终是通过PhoneLayoutInflater对象的onCreateView来创建对应的View对象的。那么具体的View的创建过程是怎么样的呢,今天我们来一起分析一下。
通常情况下,一个Activity的界面的创建是通过setContentView来引入布局。
mWindow = new PhoneWindow(this, window);
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
而Activity的setContentView方法是通过调用Window的setContentView方法,而Window是一个抽象对象,它的具体实现类就是PhoneWindow。在PhoneWindow中找到setContentView方法:
@Override
public void setContentView(int layoutResID) {
// 如果mContentParent为空时先构建
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 {
// 通过LayoutInflater解析布局
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}
可以发现,setContentView也是通过LayoutInflater加载布局加载到mContentParent中。我们再看inflate方法:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, 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();
}
}
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对象
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
// 父视图
View result = root;
try {
// Look for the root node.
int type;
// 找到root元素
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!");
}
final String name = parser.getName();
// 解析merge标签
if (TAG_MERGE.equals(name)) {
// 如果是merge标签调用新方法,将merge标签内的元素全部加载到父视图中
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// 通过xml的tag来解析根视图
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
// 不是merge标签,直接解析布局中的视图
ViewGroup.LayoutParams params = null;
if (root != null) {
// 生成布局参数
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
temp.setLayoutParams(params);
}
}
// Inflate all children under temp against its context.
// 解析temp视图下的所有view
rInflateChildren(parser, temp, attrs, true);
// 如果root不为空并且attachToRoot为true,将temp加入到父视图中
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果root为空 或者 attachToRoot为false,返回的结果就是temp
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
throw ie;
} catch (Exception e) {
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
最终调用public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
方法,其中第一个参数是xml解析器,第二个参数是要解析布局的父视图,第三个参数标识是否需要加入到父视图中。
上面的inflate方法所做的操作主要有以下几步:
- 解析xml的根标签
- 如果根标签是merge,那么调用rInflate解析,将merge标签下的所有子View直接添加到根标签中
- 如果不是merge,调用createViewFromTag解析该元素
- 调用rInflate解析temp中的子View,并将这些子View添加到temp中
- 通过attachToRoot,返回对应解析的根视图
我们先看createViewFromTag方法:
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
try {
View view;
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
// 通过.来判断是自定义View还是内置View
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) {
throw ie;
}
}
我们可以发现,解析View的时候是通过.
来判断是内置的View还是自定义的View的,那么我们就能知道为什么在写布局文件中自定义的View需要完整路径了。
在解析内置View的时候就是通过类似于PhoneLayoutInflater的onCreateView的解析方式,通过在name前加上android.view.
最终也是调用createView来解析。
而自定义view则是在调用createView(name, null, attrs)时,第二个参数的前缀传递null。
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
// 从缓存中获取view的构造函数
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) {
// 如果前缀不为空构造完整的View路径并加载该类
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
// 获取该类的构造函数
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
// 将构造函数加入缓存中
sConstructorMap.put(name, constructor);
} else {
}
Object[] args = mConstructorArgs;
args[1] = attrs;
// 通过反射构建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]));
}
return view;
}
}
createView相对简单,通过判断前缀,来构建View的完整路径,并将该类加载到虚拟机中,获取构造函数并缓存,再通过构造函数创建该View对象,并返回。这个时候我们就获得了根视图。接着调用rInflateChildren方法解析子View,并最终调用rInflate方法:
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
// 获取树的深度,通过深度优先遍历
final int depth = parser.getDepth();
int type;
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)) {
parseRequestFocus(parser, parent);
} else if (TAG_TAG.equals(name)) {// 解析tag标签
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {// 解析include标签
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {// 解析到merge标签,并报错
throw new InflateException("<merge /> must be the root element");
} else {
// 解析到普通的子View,并调用createViewFromTag获得View对象
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
// 递归解析
rInflateChildren(parser, view, attrs, true);
// 将View加入到父视图中
viewGroup.addView(view, params);
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
rInflate方法通过深度优先遍历的方式来构造视图树,当解析到一个View的时候就再次调用rInflate方法,直到将路径下的最后一个元素,并最终将View加入到父视图中。
这就是完整的View的创建流程。
网友评论