文章目录
我们每一个安卓开发者都知道xml布局可以显示界面,那么作为有追求的开发者我们要知其然更要知其所以然。搞清楚xml布局在源码层面最终是通过什么方式转换成什么?了解背后原理后又能带来什么样的收益?带着种种疑问我们来深究源码去揭开其魅力的面纱。
一、LayoutInflater类
LayoutInflater被用在哪里
有如下两个地方:
- LayoutInflater用于代码动态创建View
- LayoutInflater用于Activity界面初始化View
下面就让我们来一一介绍
1. LayoutInflater用于代码动态创建View
以下是一般从xml布局文件创建View对象的方法
方法一:
View view = LayoutInflater.from(context()).inflate(layoutResId, viewGroup, false);
方法二:
View view = View.inflate(viewGroup.getContext(), layoutResId, null);
方法三:
View view = ((LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(viewGroup.getContext(), layoutResId, null);
这三个方法内部都是context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)拿到LayoutInflater服务实现填充xml布局。
最终的调用是LayoutInflater类内部的inflate方法,如下:
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
......
//预编译:如果支持,则从布局文件xml预编译生成的dex文件,通过反射来获取对应的View,来减少xml布局用解析器解析的时间
//初始化时设置不支持
View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
if (view != null) {
return view;
}
//如果没有预编译机制看,则获取XML的资源解析器
XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
tryInflatePrecompiled()由于目前在release版本不支持,仅支持CTS tests,所以会通过Resources.getLayout方法去获取xml解析器XmlResourceParser,具体怎么获取我们在这里不做展开讨论,接下来将XmlResourceParser作为参数调用inflate()的重载方法