本文主要介绍android中布局填充器的实现,即把Xml布局文件解析成View的过程。以下源码摘自android8.0
目录
- LayoutInflater.from()
- inflate()
- 总结
一、LayoutInflater.from()
该方法最终会拿到一个PhoneLayoutInflater实例,它继承了LayoutInflater抽象类
1. 源码分析
LayoutInflater抽象类
public static LayoutInflater from(Context context) {
//假设传入的是Activity,Activity启动后初始化的上下文就是ContextImpl,Activity的启动过程
//这里不再阐述,其实是调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) {
//直接调SystemServiceRegistry的getSystemService方法
return SystemServiceRegistry.getSystemService(this, name);
}
SystemServiceRegistry类
public static Object getSystemService(ContextImpl ctx, String name) {
//SYSTEM_SERVICE_FETCHERS是个HashMap,ServiceFetcher<T>是个接口,里边只有一个getService接口方法
//这个name就是LAYOUT_INFLATER_SERVICE,因此我们看它是什么时候往HashMap中添加的,我们会发现在该类中
//会有个静态代码块
ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
return fetcher != null ? fetcher.getService(ctx) : null;
}
static{
...
//该方法会向HashMap中添加服务
registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
new CachedServiceFetcher<LayoutInflater>() {
@Override
public LayoutInflater createService(ContextImpl ctx) {
//从这里可以看到我们获取到的其实是PhoneLayoutInflater实例
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中添加服务
SYSTEM_SERVICE_FETCHERS.put(serviceName, serviceFetcher);
}
2. 调用过程
LayoutInflater.from().png二、inflate()
由上可知,其实我们获取到的其实是PhoneLayoutInflater实例,而PhoneLayoutInflater继承了LayoutInflater抽象类,其实调的是LayoutInflater中的inflate方法,我们假设调用的是inflate(R.layout.activity_main, null)方法
1. 源码分析
LayoutInflater抽象类
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
//调另一个重载的方法
return inflate(resource, root, root != null);
}
//第一个参数为布局文件id,第二参数个为null,第三个参数为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 {
//调另一个重载的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;
//找到第一个开始标签
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();
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");
}
//如果第一个标签是merge,那就调用rInflate解析
rInflate(parser, root, inflaterContext, attrs, false);
} else {
//第一个标签不是merge,就调createViewFromTag,该方法把一个标签解析成相应的View
//我们假设第一个标签是RelativeLayout
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
...
//解析RelativeLayout下面的标签,该方法和merge一样也会调到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 {
//直接调rInflate方法
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
整个过程就是先判断是否是merge标签,是merge标签就走rInflate方法,不是的话就先走createViewFromTag方法拿到第一个标签对象的View,再走rInflate方法,最后返回一颗View树,因此这里我们只需要关注createViewFromTag和rInflate这两个方法,下面先看createViewFromTag方法是如何把标签解析成对应的View的
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(TAG_1995)) {
//TAG_1995是blink字符串,即如果是眨眼标签blink,
//那就直接返回,BlinkLayout类是LayoutInflater的内部类
return new BlinkLayout(context, attrs);
}
View view;
//这些工厂默认都是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);
}
//开始解析
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
//系统控件,没有点,系统控件最终加上android.widget的前缀
//最后也是调LayoutInFlater的createView方法
view = onCreateView(parent, name, attrs);
} else {
//自定义控件,有点,不用加前缀
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
...省略try-catch...
}
protected View onCreateView(View parent, String name, AttributeSet attrs)
throws ClassNotFoundException {
//由于真正的实例是PhoneLayoutInflater,而PhoneLayoutInflater又重写了
//onCreateView方法,因此这里会调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 {
//调LayoutInflater的createView方法
//该方法会给系统控件加上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);
}
不管是自定义控件,还是系统控件最终都会调到LayoutInflater的createView方法
LayoutInflater类
//系统控件的前缀为android.widget,自定义控件的前缀是null,即没有前缀
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;
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
//缓存中没有就创建一个,系统控件会加上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中获取构造,并加入到缓存中
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;
//反射创建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...
}
从上面可以看到从标签到响应View的过程是通过反射来实现的,并且构造的获取使用了享元模式,下面看另一个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;
//注意这个循环
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标签必须是根标签,这里不应该有merge,直接抛出异常
throw new InflateException("<merge /> must be the root element");
} else {
//上面已经讲过了,该方法会把单个标签解析成对应的View
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
//rInflateChildren方法直接会掉当前这个rInflate方法,即递归解析,并且是深度优先
rInflateChildren(parser, view, attrs, true);
//添加到父View上
viewGroup.addView(view, params);
}
}
...
}
2. 调用过程
inflate.png三、总结
1、xml布局文件的解析是通过XmlPullParser,即android内置的pull解析,至于Dom解析、Sax解析、Pull解析的区别和使用自行百度
2、布局中的每个标签分为系统控件和自定义控件,它们用点来区分,有点就是自定义控件,没点就是系统控件,系统控件最终也会加上android.widget前缀形成完整路径名
3、最终每个标签都是通过反射创建拿到相应的控件实例,最终会通过深度优先的顺序解析形成一颗View树
网友评论