从这篇博客开始,我们会用几篇文章,
基于Android O的代码,分析一下View的绘制流程。
在分析具体的绘制流程前,我们先来了解一下XML中定义的View,
如何被创建和加载。
一、setContentView
在分析具体的代码前,我们先看看Android的视图结构:
如上图所示,每个Activity都与一个Window(具体来说是PhoneWindow)相关联,后者用于承载实际的用户界面。
Window是一个抽象的类,它表示屏幕上用于绘制各种UI元素及响应用户输入事件的一个矩形区域。
DecorView是一个应用窗口的根容器,它本质上是一个FrameLayout。
DecorView仅包含一个子View,它是一个垂直的LinearLayout。
该LinearLayout包含两个子元素,一个是TitleView(ActionBar的容器),
另一个是ContentView(窗口内容的容器)。
ContentView是一个FrameLayout。
我们在Activity中调用setContentView时,就是在设置它的子View。
现在我们就从Activity的setContentView开始分析,
看看XML中的View如何被一步步创建和加载。
public void setContentView(@LayoutRes int layoutResID) {
//设置Activity的contentView
getWindow().setContentView(layoutResID);
//设置TitleView, 即ActionBar
initWindowDecorActionBar();
}
.............
/**
* Creates a new ActionBar, locates the inflated ActionBarView,
* initializes the ActionBar with the view, and sets mActionBar.
*/
private void initWindowDecorActionBar() {
Window window = getWindow();
// Initializing the window decor can change window feature flags.
// Make sure that we have the correct set before performing the test below.
window.getDecorView();
//确保可以绘制ActionBar
if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
return;
}
mActionBar = new WindowDecorActionBar(this);
mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);
mWindow.setDefaultIcon(mActivityInfo.getIconResource());
mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
}
从代码来看,Activity的setContentView函数,会先加载自己的ContentView,
然后再利用initWindowDecorActionBar函数加载ActionBar。
我们主要跟进一下getWindow().setContentView函数,
即PhoneWindow中的setContentView函数。
对应的代码如下:
public void setContentView(int layoutResID) {
if (mContentParent == null) {
// mContentParent为ContentView的父容器, 即DecorView
// 若为空, 则调用installDecor()生成
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
// FEATURE_CONTENT_TRANSITIONS的用途可参考其注释
// 主要是支持动画切换Activity的content view
// mContentParent不为null, 则移除DecorView的所有子View
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
//转移到新的content view
transitionTo(newScene);
} else {
//默认在此处填充布局, 将我们在xml中定义的contentView加载到mContentParent中
mLayoutInflater.inflate(layoutResID, mContentParent);
}
.............
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
// 回调onContentChanged(), 通知Activity窗口内容发生了改变
cb.onContentChanged();
}
.........
}
从上面的代码可以看出,在setContentView函数中,
主要是通过LayoutInflater的inflate函数,来解析XML文件并填充ContentView。
二、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();
............
//parser中已经包含了XML信息
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) {
...........
//初始化一些参数
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;
// 循环查找START_TAG
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
//结束前,还未找到START_TAG, 则抛出异常
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
final String name = parser.getName();
...............
//单独处理xml中的merge标签
if (TAG_MERGE.equals(name)) {
//使用merge时,root不能为null且attachToRoot必须为true
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
// 创建出xml中的根View
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)
// 若attachToRoot参数为false,
// 则仅将父容器的布局参数设置给根View
// 否则,会将根View添加到父容器
temp.setLayoutParams(params);
}
}
............
// Inflate all children under temp against its context.
// 递归加载根View的子View
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) {
//根View被父容器“包裹”
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(....) {
.......
} finally {
// Don't retain static reference on context.
// 用类的成员来保存context, 避免内存泄露
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
..........
}
return result;
}
}
从上面的代码可以看出,当XML以merge标签开始时,
将直接调用rInflate函数来进行处理。
否则,正常情况下,会先创建出XML的根View,
然后利用rInflateChildren加载根View的子View。
最终,根据条件选择是否将根View attach到父容器中。
三、rInflate
我们先来看看rInflate对应的代码:
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;
//解析整个xml(指当前的START_TAG~END_TAG这段区域)
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
//必须从START_TAG开始解析
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>标记, 其中最终也利用rInflate、 rInflateChildren加载View
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
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);
//递归加载子View, 此时view作为新的根View
rInflateChildren(parser, view, attrs, true);
//加载完毕后,填充到父容器
viewGroup.addView(view, params);
}
//根据标志进行回调
if (pendingRequestFocus) {
parent.restoreDefaultFocus();
}
if (finishInflate) {
parent.onFinishInflate();
}
}
}
从上面代码可以看出,rInflate函数负责解析当前区域的XML,
然后创建出这段区域的根View,并利用rInflateChildren加载子View,
最终将根View填充到父容器内。
我们来看看rInflateChildren的代码:
//容易看出,实际上还是调用了rInflate函数
//即将传入的View作为新的根View进行加载
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
至此,Activity加载界面的流程分析完毕。
四、总结
从代码的角度来看,Activity加载界面的流程是比较好理解的。
整体的思想实际上可以简化为上图,其中最重要的函数是rInflate。
通过该函数,系统会以先序遍历的方式,创建XML对应的View。
简单来讲,创建View的方式类似于:
假设一段XML范围内,定义了根View及1~n个子View,
那么创建出根View后,必须先加载View 1及其所有子View,
才会开始加载View 2。