ensureOpenLocked();
//‘打开 xml 布局文件’
final long xmlBlock = nativeOpenXmlAsset(mObject, cookie, fileName);
《Android学习笔记总结+最新移动架构视频+大厂安卓面试真题+项目实战源码讲义》
【docs.qq.com/doc/DSkNLaERkbnFoS0ZF】 完整内容开源分享
if (xmlBlock == 0) {
//‘若打开失败则抛文件未找到异常’
throw new FileNotFoundException(“Asset XML file: ” + fileName);
}
final XmlBlock block = new XmlBlock(this, xmlBlock);
incRefsLocked(block.hashCode());
return block;
}
}
}
通过一个 native 方法,将布局文件读取到内存。走查到这里,有一件事可以确定,即 “解析 xml 布局文件前需要进行 IO 操作,将其读取至内存中”。
解析布局文件
读原码就好像“递归”,刚才通过不断地“递”,现在通过“归”回到那个关键方法:
public abstract class LayoutInflater {
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
…
//‘获取布局文件解析器’
final XmlResourceParser parser = res.getLayout(resource);
try {
//‘填充布局’
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
}
通过 IO 操作将布局文件读到内存后,调用了inflate()
:
public abstract class LayoutInflater {
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
…
try {
//‘根据布局文件的声明控件的标签构建 View’
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
//‘构建 View 对应的布局参数’
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);
}
}
…
//‘将 View 填充到 View 树’
if (root != null && attachToRoot) {
root.addView(temp, params);
}
…
} catch (XmlPullParserException e) {
…
} finally {
…
}
return result;
}
}
这个方法解析布局文件并根据其中声明控件的标签构建 View实例,然后将其填充到 View 树中。解析布局文件的细节在createViewFromTag()
中:
public abstract class LayoutInflater {
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,boolean igno