从这篇博客开始,我们会用几篇文章, 
基于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的contentViewgetWindow().setContentView(layoutResID);//设置TitleView, 即ActionBarinitWindowDecorActionBar();}............./*** 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();//确保可以绘制ActionBarif (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());}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

从代码来看,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的所有子ViewmContentParent.removeAllViews();}if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,getContext());//转移到新的content viewtransitionTo(newScene);} else {//默认在此处填充布局, 将我们在xml中定义的contentView加载到mContentParent中mLayoutInflater.inflate(layoutResID, mContentParent);}.............final Callback cb = getCallback();if (cb != null && !isDestroyed()) {// 回调onContentChanged(), 通知Activity窗口内容发生了改变cb.onContentChanged();}.........
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

从上面的代码可以看出,在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_TAGwhile ((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必须为trueif (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中的根Viewfinal 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的子ViewrInflateChildren(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;}    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107

从上面的代码可以看出,当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加载ViewparseInclude(parser, context, parent, attrs);} else if (TAG_MERGE.equals(name)) {throw new InflateException("<merge /> must be the root element");} else {//一般情况//根据标记,创建出Viewfinal View view = createViewFromTag(parent, name, context, attrs);final ViewGroup viewGroup = (ViewGroup) parent;final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);//递归加载子View, 此时view作为新的根ViewrInflateChildren(parser, view, attrs, true);//加载完毕后,填充到父容器viewGroup.addView(view, params);}//根据标志进行回调if (pendingRequestFocus) {parent.restoreDefaultFocus();}if (finishInflate) {parent.onFinishInflate();}}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

从上面代码可以看出,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);}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

至此,Activity加载界面的流程分析完毕。

四、总结 
 
从代码的角度来看,Activity加载界面的流程是比较好理解的。 
整体的思想实际上可以简化为上图,其中最重要的函数是rInflate。 
通过该函数,系统会以先序遍历的方式,创建XML对应的View。

简单来讲,创建View的方式类似于: 
假设一段XML范围内,定义了根View及1~n个子View, 
那么创建出根View后,必须先加载View 1及其所有子View, 
才会开始加载View 2。

版权声明:转载请注明:http://blog.csdn.net/gaugamela/article

Android O: View的绘制流程(一): 创建和加载相关推荐

  1. Android O: View的绘制流程(二):测量

    在前一篇博客Android O: View的绘制流程(一): 创建和加载中,  我们分析了系统创建和加载View的过程,这部分内容完成了View绘制的前置工作. 本文开始分析View的测量的流程. 一 ...

  2. Android O: View的绘制流程(三):布局和绘制

    前一篇文章Android O: View的绘制流程(二):测量中,  我们分析了View的测量流程.  当View测量完毕后,就要开始进行布局和绘制相关的工作,  本篇文章就来分析下这部分流程. 一. ...

  3. Android之View的绘制流程解析

    转载请标明出处:[顾林海的博客] 个人开发的微信小程序,目前功能是书籍推荐,后续会完善一些新功能,希望大家多多支持! ##前言 自定义View在Android中占据着非常重要的地位,因此了解View的 ...

  4. 从源码解析-Android中View的绘制流程及performTraversals方法

    谈谈Activity的setContentView是怎么加载XML视图的 谈谈Activity的View怎么与View绘制工具ViewRootImpl关联的 在前面两篇文章中分析了View是如何跟绘制 ...

  5. android自定义view流程,Android 自定义View--从源码理解View的绘制流程

    前言 在Android的世界里,View扮演着很重要的角色,它是Android世界在视觉上的具体呈现.Android系统本身也提供了很多种原生控件供我们使用,然而在日常的开发中我们很多时候需要去实现一 ...

  6. Android自定义View系列之详解View的绘制流程

    目录 一.开场白 二.View的绘制流程 2.1测量的过程 2.2布局的过程 2.3绘制的过程 一.开场白 开讲之前我们先预设一种自定义ViewGroup的场景:我们知道LinearLayout.Fr ...

  7. 【Android面试】View的绘制流程

    目录 View的绘制流程简介 Activity和window和view 的关系 Activity和Window是什么时候建立联系的呢? ViewRootImpl View的绘制流程总结 View的绘制 ...

  8. Android View的绘制流程(1) -- 测量onMeasure

    鉴于是首篇讲解自定义view流程,之前也在网上搜了一些博主的博客看了看,都是大同小异,今天抽时间自己总结一下,分享一下自己的感悟,也算是一篇笔记. (本篇为开头篇,稍微讲述一下有关的东西) View的 ...

  9. Android进阶知识:绘制流程(上)

    1.前言 之前写过一篇Android进阶知识:事件分发与滑动冲突,主要研究的是关于Android中View事件分发与响应的流程.关于View除了事件传递流程还有一个很重要的就是View的绘制流程.一个 ...

最新文章

  1. 公开课报名 | 基于自定义模板的OCR结果的结构化处理技术
  2. Vue-router路由使用,单页面的实现
  3. visual studio(vs)中项目解决方案的目录组织安排
  4. Android Studio安装、配置教程全 - 安卓开发环境的配置手册
  5. 综述|重邮高新波等最新《少样本目标检测算法》
  6. paip.日期时间操作以及时间戳uapi php java python 总结
  7. SAP 服务器文件上传和下载
  8. SpringBoot+Vue项目校园闲置物品交易系统
  9. 圣思园的随堂视频发布了
  10. 小程序UI与传统HTML5区别
  11. OpenCV中的图像处理 —— 轮廓入门+轮廓特征
  12. 大规模WebGL应用引发浏览器崩溃的几种情况及解决办法
  13. 装了linux的u盘格式化,u盘格式化容量变小了u盘安装linuxcentos
  14. 浅陌初心 / vue3-admin-element
  15. 并发编程之循环屏障CyclicBarrier
  16. 仿淘宝天猫双11下拉倒计时领取豆子
  17. ucenter单点登录
  18. 机器学习三大基本任务_Task01
  19. PCIe接口二,三事
  20. ipaddress库:Python中网络地址的处理

热门文章

  1. poj 3077Rounders(模拟)
  2. JavaScript中Promises/A+规范的实现
  3. 让你的网站在移动端健步如飞
  4. '0','\0',NULL,EOF的区别
  5. 结对项目——电梯调度算法的实现和测试
  6. Struts Validator验证器使用指南
  7. 使用echo输出一绝对路径,使用egrep取出其基名
  8. 深度学习笔记:windows+tensorflow 指定GPU占用内存(解决gpu爆炸问题)
  9. [云炬创业管理笔记]第一章讨论3
  10. 2020教资高频考点作文素材汇总