您的位置:首页 > 移动开发 > Android开发

Android应用层View绘制流程与源码分析

2015-06-08 14:32 573 查看

1 背景

还记得前面《Android应用setContentView与LayoutInflater加载解析机制源码分析》这篇文章吗?我们有分析到Activity中界面加载显示的基本流程原理,记不记得最终分析结果就是下面的关系:



看见没有,如上图中id为content的内容就是整个View树的结构,所以对每个具体View对象的操作,其实就是个递归的实现。

前面《Android触摸屏事件派发机制详解与源码分析一(View篇)》文章的3-1小节说过Android中的任何一个布局、任何一个控件其实都是直接或间接继承自View实现的,当然也包括我们后面一步一步引出的自定义控件也不例外,所以说这些View应该都具有相同的绘制流程与机制才能显示到屏幕上(因为他们都具备相同的父类View,可能每个控件的具体绘制逻辑有差异,但是主流程都是一样的)。经过总结发现每一个View的绘制过程都必须经历三个最主要的过程,也就是measure、layout和draw。

既然一个View的绘制主要流程是这三步,那一定有一个开始地方呀,就像一个类从main函数执行一样呀。对于View的绘制开始调运地方这里先给出结论,本文后面会反过来分析原因的,先往下看就行。具体结论如下:

整个View树的绘图流程是在ViewRootImpl类的performTraversals()方法(这个方法巨长)开始的,该函数做的执行过程主要是根据之前设置的状态,判断是否重新计算视图大小(measure)、是否重新放置视图的位置(layout)、以及是否重绘 (draw),其核心也就是通过判断来选择顺序执行这三个方法中的哪个,如下:

<code class="language-java hljs  has-numbering"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">performTraversals</span>() {
......
<span class="hljs-comment">//最外层的根视图的widthMeasureSpec和heightMeasureSpec由来</span>
<span class="hljs-comment">//lp.width和lp.height在创建ViewGroup实例时等于MATCH_PARENT</span>
<span class="hljs-keyword">int</span> childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
<span class="hljs-keyword">int</span> childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
......
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
......
mView.layout(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, mView.getMeasuredWidth(), mView.getMeasuredHeight());
......
mView.draw(canvas);
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li></ul>
<code class="language-java hljs  has-numbering">    <span class="hljs-javadoc">/**
* Figures out the measure spec for the root view in a window based on it's
* layout params.
*
*<span class="hljs-javadoctag"> @param</span> windowSize
*            The available width or height of the window
*
*<span class="hljs-javadoctag"> @param</span> rootDimension
*            The layout params for one dimension (width or height) of the
*            window.
*
*<span class="hljs-javadoctag"> @return</span> The measure spec to use to measure the root view.
*/</span>
<span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getRootMeasureSpec</span>(<span class="hljs-keyword">int</span> windowSize, <span class="hljs-keyword">int</span> rootDimension) {
<span class="hljs-keyword">int</span> measureSpec;
<span class="hljs-keyword">switch</span> (rootDimension) {

<span class="hljs-keyword">case</span> ViewGroup.LayoutParams.MATCH_PARENT:
<span class="hljs-comment">// Window can't resize. Force root view to be windowSize.</span>
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
<span class="hljs-keyword">break</span>;
......
}
<span class="hljs-keyword">return</span> measureSpec;
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li></ul>

可以看见这个方法的注释说是用来测Root View的。上面传入参数后这个函数走的是MATCH_PARENT,使用MeasureSpec.makeMeasureSpec方法组装一个MeasureSpec,MeasureSpec的specMode等于EXACTLY,specSize等于windowSize,也就是为何根视图总是全屏的原因。

其中的mView就是View对象。如下就是整个流程的大致流程图:



如下我们就依据View绘制的这三个主要流程进行详细剖析(基于Android5.1.1 API 22源码进行分析)。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

2 View绘制流程第一步:递归measure源码分析

整个View树的源码measure流程图如下:



2-1 measure源码分析

先看下View的measure方法源码,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-javadoc">/**
* <p>
* This is called to find out how big a view should be. The parent
* supplies constraint information in the width and height parameters.
* </p>
*
* <p>
* The actual measurement work of a view is performed in
* {@link #onMeasure(int, int)}, called by this method. Therefore, only
* {@link #onMeasure(int, int)} can and must be overridden by subclasses.
* </p>
*
*
*<span class="hljs-javadoctag"> @param</span> widthMeasureSpec Horizontal space requirements as imposed by the
*        parent
*<span class="hljs-javadoctag"> @param</span> heightMeasureSpec Vertical space requirements as imposed by the
*        parent
*
*<span class="hljs-javadoctag"> @see</span> #onMeasure(int, int)
*/</span>
<span class="hljs-comment">//final方法,子类不可重写</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">void</span> <span class="hljs-title">measure</span>(<span class="hljs-keyword">int</span> widthMeasureSpec, <span class="hljs-keyword">int</span> heightMeasureSpec) {
......
<span class="hljs-comment">//回调onMeasure()方法</span>
onMeasure(widthMeasureSpec, heightMeasureSpec);
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li></ul>

看见注释信息没有,他告诉你了很多重要信息。为整个View树计算实际的大小,然后设置实际的高和宽,每个View控件的实际宽高都是由父视图和自身决定的。实际的测量是在onMeasure方法进行,所以在View的子类需要重写onMeasure方法,这是因为measure方法是final的,不允许重载,所以View子类只能通过重载onMeasure来实现自己的测量逻辑。

这个方法的两个参数都是父View传递过来的,也就是代表了父view的规格。他由两部分组成,高16位表示MODE,定义在MeasureSpec类(View的内部类)中,有三种类型,MeasureSpec.EXACTLY表示确定大小, MeasureSpec.AT_MOST表示最大大小, MeasureSpec.UNSPECIFIED不确定。低16位表示size,也就是父View的大小。对于系统Window类的DecorVIew对象Mode一般都为MeasureSpec.EXACTLY ,而size分别对应屏幕宽高。对于子View来说大小是由父View和子View共同决定的。

在这里可以看出measure方法最终回调了View的onMeasure方法,我们来看下View的onMeasure源码,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-javadoc">/**
* <p>
* Measure the view and its content to determine the measured width and the
* measured height. This method is invoked by {@link #measure(int, int)} and
* should be overriden by subclasses to provide accurate and efficient
* measurement of their contents.
* </p>
*
* <p>
* <strong>CONTRACT:</strong> When overriding this method, you
* <em>must</em> call {@link #setMeasuredDimension(int, int)} to store the
* measured width and height of this view. Failure to do so will trigger an
* <code>IllegalStateException</code>, thrown by
* {@link #measure(int, int)}. Calling the superclass'
* {@link #onMeasure(int, int)} is a valid use.
* </p>
*
* <p>
* The base class implementation of measure defaults to the background size,
* unless a larger size is allowed by the MeasureSpec. Subclasses should
* override {@link #onMeasure(int, int)} to provide better measurements of
* their content.
* </p>
*
* <p>
* If this method is overridden, it is the subclass's responsibility to make
* sure the measured height and width are at least the view's minimum height
* and width ({@link #getSuggestedMinimumHeight()} and
* {@link #getSuggestedMinimumWidth()}).
* </p>
*
*<span class="hljs-javadoctag"> @param</span> widthMeasureSpec horizontal space requirements as imposed by the parent.
*                         The requirements are encoded with
*                         {@link android.view.View.MeasureSpec}.
*<span class="hljs-javadoctag"> @param</span> heightMeasureSpec vertical space requirements as imposed by the parent.
*                         The requirements are encoded with
*                         {@link android.view.View.MeasureSpec}.
*
*<span class="hljs-javadoctag"> @see</span> #getMeasuredWidth()
*<span class="hljs-javadoctag"> @see</span> #getMeasuredHeight()
*<span class="hljs-javadoctag"> @see</span> #setMeasuredDimension(int, int)
*<span class="hljs-javadoctag"> @see</span> #getSuggestedMinimumHeight()
*<span class="hljs-javadoctag"> @see</span> #getSuggestedMinimumWidth()
*<span class="hljs-javadoctag"> @see</span> android.view.View.MeasureSpec#getMode(int)
*<span class="hljs-javadoctag"> @see</span> android.view.View.MeasureSpec#getSize(int)
*/</span>
<span class="hljs-comment">//View的onMeasure默认实现方法</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onMeasure</span>(<span class="hljs-keyword">int</span> widthMeasureSpec, <span class="hljs-keyword">int</span> heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li></ul>

看见没有,其实注释已经很详细了(自定义View重写该方法的指导操作注释都有说明),不做过多解释。

对于非ViewGroup的View而言,通过调用上面默认的onMeasure即可完成View的测量,当然你也可以重载onMeasure并调用setMeasuredDimension来设置任意大小的布局,但一般不这么做,因为这种做法不太好,至于为何不好,后面分析完你就明白了。

我们可以看见onMeasure默认的实现仅仅调用了setMeasuredDimension,setMeasuredDimension函数是一个很关键的函数,它对View的成员变量mMeasuredWidth和mMeasuredHeight变量赋值,measure的主要目的就是对View树中的每个View的mMeasuredWidth和mMeasuredHeight进行赋值,所以一旦这两个变量被赋值意味着该View的测量工作结束。既然这样那我们就看看设置的默认尺寸大小吧,可以看见setMeasuredDimension传入的参数都是通过getDefaultSize返回的,所以再来看下getDefaultSize方法源码,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getDefaultSize</span>(<span class="hljs-keyword">int</span> size, <span class="hljs-keyword">int</span> measureSpec) {
<span class="hljs-keyword">int</span> result = size;
<span class="hljs-comment">//通过MeasureSpec解析获取mode与size</span>
<span class="hljs-keyword">int</span> specMode = MeasureSpec.getMode(measureSpec);
<span class="hljs-keyword">int</span> specSize = MeasureSpec.getSize(measureSpec);

<span class="hljs-keyword">switch</span> (specMode) {
<span class="hljs-keyword">case</span> MeasureSpec.UNSPECIFIED:
result = size;
<span class="hljs-keyword">break</span>;
<span class="hljs-keyword">case</span> MeasureSpec.AT_MOST:
<span class="hljs-keyword">case</span> MeasureSpec.EXACTLY:
result = specSize;
<span class="hljs-keyword">break</span>;
}
<span class="hljs-keyword">return</span> result;
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li></ul>

看见没有,如果specMode等于AT_MOST或EXACTLY就返回specSize,这就是系统默认的规格。

回过头继续看上面onMeasure方法,其中getDefaultSize参数的widthMeasureSpec和heightMeasureSpec都是由父View传递进来的。getSuggestedMinimumWidth与getSuggestedMinimumHeight都是View的方法,具体如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getSuggestedMinimumWidth</span>() {
<span class="hljs-keyword">return</span> (mBackground == <span class="hljs-keyword">null</span>) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}

<span class="hljs-keyword">protected</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getSuggestedMinimumHeight</span>() {
<span class="hljs-keyword">return</span> (mBackground == <span class="hljs-keyword">null</span>) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());

}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li></ul>

看见没有,建议的最小宽度和高度都是由View的Background尺寸与通过设置View的miniXXX属性共同决定的。

到此一次最基础的元素View的measure过程就完成了。上面说了View实际是嵌套的,而且measure是递归传递的,所以每个View都需要measure。实际能够嵌套的View一般都是ViewGroup的子类,所以在ViewGroup中定义了measureChildren, measureChild, measureChildWithMargins方法来对子视图进行测量,measureChildren内部实质只是循环调用measureChild,measureChild和measureChildWithMargins的区别就是是否把margin和padding也作为子视图的大小。如下我们以ViewGroup中稍微复杂的measureChildWithMargins方法来分析:

<code class="language-java hljs  has-numbering">    <span class="hljs-javadoc">/**
* Ask one of the children of this view to measure itself, taking into
* account both the MeasureSpec requirements for this view and its padding
* and margins. The child must have MarginLayoutParams The heavy lifting is
* done in getChildMeasureSpec.
*
*<span class="hljs-javadoctag"> @param</span> child The child to measure
*<span class="hljs-javadoctag"> @param</span> parentWidthMeasureSpec The width requirements for this view
*<span class="hljs-javadoctag"> @param</span> widthUsed Extra space that has been used up by the parent
*        horizontally (possibly by other children of the parent)
*<span class="hljs-javadoctag"> @param</span> parentHeightMeasureSpec The height requirements for this view
*<span class="hljs-javadoctag"> @param</span> heightUsed Extra space that has been used up by the parent
*        vertically (possibly by other children of the parent)
*/</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">measureChildWithMargins</span>(View child,
<span class="hljs-keyword">int</span> parentWidthMeasureSpec, <span class="hljs-keyword">int</span> widthUsed,
<span class="hljs-keyword">int</span> parentHeightMeasureSpec, <span class="hljs-keyword">int</span> heightUsed) {
<span class="hljs-comment">//获取子视图的LayoutParams</span>
<span class="hljs-keyword">final</span> MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
<span class="hljs-comment">//调整MeasureSpec</span>
<span class="hljs-comment">//通过这两个参数以及子视图本身的LayoutParams来共同决定子视图的测量规格</span>
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
+ widthUsed, lp.width);
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
+ heightUsed, lp.height);
<span class="hljs-comment">//调运子View的measure方法,子View的measure中会回调子View的onMeasure方法</span>
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li></ul>

关于该方法的参数等说明注释已经描述的够清楚了。该方法就是对父视图提供的measureSpec参数结合自身的LayoutParams参数进行了调整,然后再来调用child.measure()方法,具体通过方法getChildMeasureSpec来进行参数调整。所以我们继续看下getChildMeasureSpec方法代码,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getChildMeasureSpec</span>(<span class="hljs-keyword">int</span> spec, <span class="hljs-keyword">int</span> padding, <span class="hljs-keyword">int</span> childDimension) {
<span class="hljs-comment">//获取当前Parent View的Mode和Size</span>
<span class="hljs-keyword">int</span> specMode = MeasureSpec.getMode(spec);
<span class="hljs-keyword">int</span> specSize = MeasureSpec.getSize(spec);
<span class="hljs-comment">//获取Parent size与padding差值(也就是Parent剩余大小),若差值小于0直接返回0</span>
<span class="hljs-keyword">int</span> size = Math.max(<span class="hljs-number">0</span>, specSize - padding);
<span class="hljs-comment">//定义返回值存储变量</span>
<span class="hljs-keyword">int</span> resultSize = <span class="hljs-number">0</span>;
<span class="hljs-keyword">int</span> resultMode = <span class="hljs-number">0</span>;
<span class="hljs-comment">//依据当前Parent的Mode进行switch分支逻辑</span>
<span class="hljs-keyword">switch</span> (specMode) {
<span class="hljs-comment">// Parent has imposed an exact size on us</span>
<span class="hljs-comment">//默认Root View的Mode就是EXACTLY</span>
<span class="hljs-keyword">case</span> MeasureSpec.EXACTLY:
<span class="hljs-keyword">if</span> (childDimension >= <span class="hljs-number">0</span>) {
<span class="hljs-comment">//如果child的layout_wOrh属性在xml或者java中给予具体大于等于0的数值</span>
<span class="hljs-comment">//设置child的size为真实layout_wOrh属性值,mode为EXACTLY</span>
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (childDimension == LayoutParams.MATCH_PARENT) {
<span class="hljs-comment">//如果child的layout_wOrh属性在xml或者java中给予MATCH_PARENT</span>
<span class="hljs-comment">// Child wants to be our size. So be it.</span>
<span class="hljs-comment">//设置child的size为size,mode为EXACTLY</span>
resultSize = size;
resultMode = MeasureSpec.EXACTLY;
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (childDimension == LayoutParams.WRAP_CONTENT) {
<span class="hljs-comment">//如果child的layout_wOrh属性在xml或者java中给予WRAP_CONTENT</span>
<span class="hljs-comment">//设置child的size为size,mode为AT_MOST</span>
<span class="hljs-comment">// Child wants to determine its own size. It can't be</span>
<span class="hljs-comment">// bigger than us.</span>
resultSize = size;
resultMode = MeasureSpec.AT_MOST;
}
<span class="hljs-keyword">break</span>;
......
<span class="hljs-comment">//其他Mode分支类似</span>
}
<span class="hljs-comment">//将mode与size通过MeasureSpec方法整合为32位整数返回</span>
<span class="hljs-keyword">return</span> MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li></ul>

可以看见,getChildMeasureSpec的逻辑是通过其父View提供的MeasureSpec参数得到specMode和specSize,然后根据计算出来的specMode以及子View的childDimension(layout_width或layout_height)来计算自身的measureSpec,如果其本身包含子视图,则计算出来的measureSpec将作为调用其子视图measure函数的参数,同时也作为自身调用setMeasuredDimension的参数,如果其不包含子视图则默认情况下最终会调用onMeasure的默认实现,并最终调用到setMeasuredDimension。

所以可以看见onMeasure的参数其实就是这么计算出来的。同时从上面的分析可以看出来,最终决定View的measure大小是View的setMeasuredDimension方法,所以我们可以通过setMeasuredDimension设定死值来设置View的mMeasuredWidth和mMeasuredHeight的大小,但是一个好的自定义View应该会根据子视图的measureSpec来设置mMeasuredWidth和mMeasuredHeight的大小,这样的灵活性更大,所以这也就是上面分析onMeasure时说View的onMeasure最好不要重写死值的原因。

可以看见当通过setMeasuredDimension方法最终设置完成View的measure之后View的mMeasuredWidth和mMeasuredHeight成员才会有具体的数值,所以如果我们自定义的View或者使用现成的View想通过getMeasuredWidth()和getMeasuredHeight()方法来获取View测量的宽高,必须保证这两个方法在onMeasure流程之后被调用才能返回有效值。

还记得前面《Android应用setContentView与LayoutInflater加载解析机制源码分析》文章3-3小节探讨的inflate方法加载一些布局显示时指定的大小失效问题吗?当时只给出了结论,现在给出了详细原因分析,我想不需要再做过多解释了吧。

至此整个View绘制流程的第一步就分析完成了,可以看见,相对来说还是比较复杂的,接下来进行小结。

2-2 measure原理总结

通过上面分析可以看出measure过程主要就是从顶层父View向子View递归调用view.measure方法(measure中又回调onMeasure方法)的过程。具体measure核心主要有如下几点:

MeasureSpec(View的内部类)测量规格为int型,值由高16位规格模式specMode和低16位具体尺寸specSize组成。其中specMode只有三种值:

<code class="language-txt hljs cs has-numbering">MeasureSpec.EXACTLY <span class="hljs-comment">//确定模式,父View希望子View的大小是确定的,由specSize决定;</span>
MeasureSpec.AT_MOST <span class="hljs-comment">//最多模式,父View希望子View的大小最多是specSize指定的值;</span>
MeasureSpec.UNSPECIFIED <span class="hljs-comment">//未指定模式,父View完全依据子View的设计值来决定; </span></code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li></ul>


View的measure方法是final的,不允许重载,View子类只能重载onMeasure来完成自己的测量逻辑。

最顶层DecorView测量时的MeasureSpec是由ViewRootImpl中getRootMeasureSpec方法确定的(LayoutParams宽高参数均为MATCH_PARENT,specMode是EXACTLY,specSize为物理屏幕大小)。

ViewGroup类提供了measureChild,measureChild和measureChildWithMargins方法,简化了父子View的尺寸计算。

只要是ViewGroup的子类就必须要求LayoutParams继承子MarginLayoutParams,否则无法使用layout_margin参数。

View的布局大小由父View和子View共同决定。

使用View的getMeasuredWidth()和getMeasuredHeight()方法来获取View测量的宽高,必须保证这两个方法在onMeasure流程之后被调用才能返回有效值。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

3 View绘制流程第二步:递归layout源码分析

在上面的背景介绍就说过,当ViewRootImpl的performTraversals中measure执行完成以后会接着执行mView.layout,具体如下:

<code class="language-java hljs  has-numbering"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">performTraversals</span>() {
......
mView.layout(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, mView.getMeasuredWidth(), mView.getMeasuredHeight());
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li></ul>

可以看见layout方法接收四个参数,这四个参数分别代表相对Parent的左、上、右、下坐标。而且还可以看见左上都为0,右下分别为上面刚刚测量的width和height。

至此又回归到View的layout(int l, int t, int r, int b)方法中去实现具体逻辑了,所以接下来我们开始分析View的layout过程。

整个View树的layout递归流程图如下:



3-1 layout源码分析

layout既然也是递归结构,那我们先看下ViewGroup的layout方法,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">void</span> <span class="hljs-title">layout</span>(<span class="hljs-keyword">int</span> l, <span class="hljs-keyword">int</span> t, <span class="hljs-keyword">int</span> r, <span class="hljs-keyword">int</span> b) {
......
<span class="hljs-keyword">super</span>.layout(l, t, r, b);
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li></ul>

看着没有?ViewGroup的layout方法实质还是调运了View父类的layout方法,所以我们看下View的layout源码,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">layout</span>(<span class="hljs-keyword">int</span> l, <span class="hljs-keyword">int</span> t, <span class="hljs-keyword">int</span> r, <span class="hljs-keyword">int</span> b) {
......
<span class="hljs-comment">//实质都是调用setFrame方法把参数分别赋值给mLeft、mTop、mRight和mBottom这几个变量</span>
<span class="hljs-comment">//判断View的位置是否发生过变化,以确定有没有必要对当前的View进行重新layout</span>
<span class="hljs-keyword">boolean</span> changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
<span class="hljs-comment">//需要重新layout</span>
<span class="hljs-keyword">if</span> (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
<span class="hljs-comment">//回调onLayout</span>
onLayout(changed, l, t, r, b);
......
}
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li></ul>

看见没有,类似measure过程,lauout调运了onLayout方法。

对比上面View的layout和ViewGroup的layout方法可以发现,View的layout方法是可以在子类重写的,而ViewGroup的layout是不能在子类重写的,言外之意就是说ViewGroup中只能通过重写onLayout方法。那我们接下来看下ViewGroup的onLayout方法,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onLayout</span>(<span class="hljs-keyword">boolean</span> changed,
<span class="hljs-keyword">int</span> l, <span class="hljs-keyword">int</span> t, <span class="hljs-keyword">int</span> r, <span class="hljs-keyword">int</span> b);</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li></ul>

看见没有?ViewGroup的onLayout()方法竟然是一个抽象方法,这就是说所有ViewGroup的子类都必须重写这个方法。所以在自定义ViewGroup控件中,onLayout配合onMeasure方法一起使用可以实现自定义View的复杂布局。自定义View首先调用onMeasure进行测量,然后调用onLayout方法动态获取子View和子View的测量大小,然后进行layout布局。重载onLayout的目的就是安排其children在父View的具体位置,重载onLayout通常做法就是写一个for循环调用每一个子视图的layout(l,
t, r, b)函数,传入不同的参数l, t, r, b来确定每个子视图在父视图中的显示位置。

再看下View的onLayout方法源码,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onLayout</span>(<span class="hljs-keyword">boolean</span> changed, <span class="hljs-keyword">int</span> left, <span class="hljs-keyword">int</span> top, <span class="hljs-keyword">int</span> right, <span class="hljs-keyword">int</span> bottom) {
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li></ul>

我勒个去!是一个空方法,没啥可看的。

既然这样那我们只能分析一个现有的继承ViewGroup的控件了,就拿LinearLayout来说吧,如下是LinearLayout中onLayout的一些代码:

<code class="language-java hljs  has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LinearLayout</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ViewGroup</span> {</span>
<span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onLayout</span>(<span class="hljs-keyword">boolean</span> changed, <span class="hljs-keyword">int</span> l, <span class="hljs-keyword">int</span> t, <span class="hljs-keyword">int</span> r, <span class="hljs-keyword">int</span> b) {
<span class="hljs-keyword">if</span> (mOrientation == VERTICAL) {
layoutVertical(l, t, r, b);
} <span class="hljs-keyword">else</span> {
layoutHorizontal(l, t, r, b);
}
}
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li></ul>

看见没有,LinearLayout的layout过程是分Vertical和Horizontal的,这个就是xml布局的orientation属性设置的,我们为例说明ViewGroup的onLayout重写一般步骤就拿这里的VERTICAL模式来解释吧,如下是layoutVertical方法源码:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">void</span> layoutVertical(<span class="hljs-keyword">int</span> left, <span class="hljs-keyword">int</span> top, <span class="hljs-keyword">int</span> right, <span class="hljs-keyword">int</span> bottom) {
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> paddingLeft = mPaddingLeft;

<span class="hljs-keyword">int</span> childTop;
<span class="hljs-keyword">int</span> childLeft;

<span class="hljs-comment">// Where right end of child should go</span>
<span class="hljs-comment">//计算父窗口推荐的子View宽度</span>
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> width = right - left;
<span class="hljs-comment">//计算父窗口推荐的子View右侧位置</span>
<span class="hljs-keyword">int</span> childRight = width - mPaddingRight;

<span class="hljs-comment">// Space available for child</span>
<span class="hljs-comment">//child可使用空间大小</span>
<span class="hljs-keyword">int</span> childSpace = width - paddingLeft - mPaddingRight;
<span class="hljs-comment">//通过ViewGroup的getChildCount方法获取ViewGroup的子View个数</span>
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> count = getVirtualChildCount();
<span class="hljs-comment">//获取Gravity属性设置</span>
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
<span class="hljs-comment">//依据majorGravity计算childTop的位置值</span>
<span class="hljs-keyword">switch</span> (majorGravity) {
<span class="hljs-keyword">case</span> Gravity.BOTTOM:
<span class="hljs-comment">// mTotalLength contains the padding already</span>
childTop = mPaddingTop + bottom - top - mTotalLength;
<span class="hljs-keyword">break</span>;

<span class="hljs-comment">// mTotalLength contains the padding already</span>
<span class="hljs-keyword">case</span> Gravity.CENTER_VERTICAL:
childTop = mPaddingTop + (bottom - top - mTotalLength) / <span class="hljs-number">2</span>;
<span class="hljs-keyword">break</span>;

<span class="hljs-keyword">case</span> Gravity.TOP:
<span class="hljs-keyword">default</span>:
childTop = mPaddingTop;
<span class="hljs-keyword">break</span>;
}
<span class="hljs-comment">//重点!!!开始遍历</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < count; i++) {
<span class="hljs-keyword">final</span> View child = getVirtualChildAt(i);
<span class="hljs-keyword">if</span> (child == <span class="hljs-keyword">null</span>) {
childTop += measureNullChild(i);
} <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (child.getVisibility() != GONE) {
<span class="hljs-comment">//LinearLayout中其子视图显示的宽和高由measure过程来决定的,因此measure过程的意义就是为layout过程提供视图显示范围的参考值</span>
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> childWidth = child.getMeasuredWidth();
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> childHeight = child.getMeasuredHeight();
<span class="hljs-comment">//获取子View的LayoutParams</span>
<span class="hljs-keyword">final</span> LinearLayout.LayoutParams lp =
(LinearLayout.LayoutParams) child.getLayoutParams();

<span class="hljs-keyword">int</span> gravity = lp.gravity;
<span class="hljs-keyword">if</span> (gravity < <span class="hljs-number">0</span>) {
gravity = minorGravity;
}
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> layoutDirection = getLayoutDirection();
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
<span class="hljs-comment">//依据不同的absoluteGravity计算childLeft位置</span>
<span class="hljs-keyword">switch</span> (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
<span class="hljs-keyword">case</span> Gravity.CENTER_HORIZONTAL:
childLeft = paddingLeft + ((childSpace - childWidth) / <span class="hljs-number">2</span>)
+ lp.leftMargin - lp.rightMargin;
<span class="hljs-keyword">break</span>;

<span class="hljs-keyword">case</span> Gravity.RIGHT:
childLeft = childRight - childWidth - lp.rightMargin;
<span class="hljs-keyword">break</span>;

<span class="hljs-keyword">case</span> Gravity.LEFT:
<span class="hljs-keyword">default</span>:
childLeft = paddingLeft + lp.leftMargin;
<span class="hljs-keyword">break</span>;
}

<span class="hljs-keyword">if</span> (hasDividerBeforeChildAt(i)) {
childTop += mDividerHeight;
}

childTop += lp.topMargin;
<span class="hljs-comment">//通过垂直排列计算调运child的layout设置child的位置</span>
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

i += getChildrenSkipCount(child, i);
}
}
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li><li>53</li><li>54</li><li>55</li><li>56</li><li>57</li><li>58</li><li>59</li><li>60</li><li>61</li><li>62</li><li>63</li><li>64</li><li>65</li><li>66</li><li>67</li><li>68</li><li>69</li><li>70</li><li>71</li><li>72</li><li>73</li><li>74</li><li>75</li><li>76</li><li>77</li><li>78</li><li>79</li><li>80</li><li>81</li><li>82</li><li>83</li><li>84</li><li>85</li><li>86</li><li>87</li></ul>

从上面分析的ViewGroup子类LinearLayout的onLayout实现代码可以看出,一般情况下layout过程会参考measure过程中计算得到的mMeasuredWidth和mMeasuredHeight来安排子View在父View中显示的位置,但这不是必须的,measure过程得到的结果可能完全没有实际用处,特别是对于一些自定义的ViewGroup,其子View的个数、位置和大小都是固定的,这时候我们可以忽略整个measure过程,只在layout函数中传入的4个参数来安排每个子View的具体位置。

到这里就不得不提getWidth()、getHeight()和getMeasuredWidth()、getMeasuredHeight()这两对方法之间的区别(上面分析measure过程已经说过getMeasuredWidth()、getMeasuredHeight()必须在onMeasure之后使用才有效)。可以看出来getWidth()与getHeight()方法必须在layout(int l, int t, int r, int b)执行之后才有效。那我们看下View源码中这些方法的实现吧,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getMeasuredWidth</span>() {
<span class="hljs-keyword">return</span> mMeasuredWidth & MEASURED_SIZE_MASK;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getMeasuredHeight</span>() {
<span class="hljs-keyword">return</span> mMeasuredHeight & MEASURED_SIZE_MASK;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getWidth</span>() {
<span class="hljs-keyword">return</span> mRight - mLeft;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getHeight</span>() {
<span class="hljs-keyword">return</span> mBottom - mTop;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getLeft</span>() {
<span class="hljs-keyword">return</span> mLeft;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getRight</span>() {
<span class="hljs-keyword">return</span> mRight;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getTop</span>() {
<span class="hljs-keyword">return</span> mTop;
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getBottom</span>() {
<span class="hljs-keyword">return</span> mBottom;
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li></ul>

这也解释了为什么有些情况下getWidth()和getMeasuredWidth()以及getHeight()和getMeasuredHeight()会得到不同的值,所以这里不做过多解释。

到此整个View的layout过程分析就算结束了,接下来进行一些总结工作。

3-2 layout原理总结

整个layout过程比较容易理解,从上面分析可以看出layout也是从顶层父View向子View的递归调用view.layout方法的过程,即父View根据上一步measure子View所得到的布局大小和布局参数,将子View放在合适的位置上。具体layout核心主要有以下几点:

View.layout方法可被重载,ViewGroup.layout为final的不可重载,ViewGroup.onLayout为abstract的,子类必须重载实现自己的位置逻辑。

measure操作完成后得到的是对每个View经测量过的measuredWidth和measuredHeight,layout操作完成之后得到的是对每个View进行位置分配后的mLeft、mTop、mRight、mBottom,这些值都是相对于父View来说的。

凡是layout_XXX的布局属性基本都针对的是包含子View的ViewGroup的,当对一个没有父容器的View设置相关layout_XXX属性是没有任何意义的(前面《Android应用setContentView与LayoutInflater加载解析机制源码分析》也有提到过)。

使用View的getWidth()和getHeight()方法来获取View测量的宽高,必须保证这两个方法在onLayout流程之后被调用才能返回有效值。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

4 View绘制流程第三步:递归draw源码分析

在上面的背景介绍就说过,当ViewRootImpl的performTraversals中measure和layout执行完成以后会接着执行mView.layout,具体如下:

<code class="language-java hljs  has-numbering"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">performTraversals</span>() {
......
<span class="hljs-keyword">final</span> Rect dirty = mDirty;
......
canvas = mSurface.lockCanvas(dirty);
......
mView.draw(canvas);
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li></ul>

draw过程也是在ViewRootImpl的performTraversals()内部调运的,其调用顺序在measure()和layout()之后,这里的mView对于Actiity来说就是PhoneWindow.DecorView,ViewRootImpl中的代码会创建一个Canvas对象,然后调用View的draw()方法来执行具体的绘制工。所以又回归到了ViewGroup与View的树状递归draw过程。

先来看下View树的递归draw流程图,如下:



如下我们详细分析这一过程。

4-1 draw源码分析

由于ViewGroup没有重写View的draw方法,所以如下直接从View的draw方法开始分析:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">draw</span>(Canvas canvas) {
......
<span class="hljs-comment">/*
* Draw traversal performs several drawing steps which must be executed
* in the appropriate order:
*
*      1. Draw the background
*      2. If necessary, save the canvas' layers to prepare for fading
*      3. Draw view's content
*      4. Draw children
*      5. If necessary, draw the fading edges and restore layers
*      6. Draw decorations (scrollbars for instance)
*/</span>

<span class="hljs-comment">// Step 1, draw the background, if needed</span>
......
<span class="hljs-keyword">if</span> (!dirtyOpaque) {
drawBackground(canvas);
}

<span class="hljs-comment">// skip step 2 & 5 if possible (common case)</span>
......

<span class="hljs-comment">// Step 2, save the canvas' layers</span>
......
<span class="hljs-keyword">if</span> (drawTop) {
canvas.saveLayer(left, top, right, top + length, <span class="hljs-keyword">null</span>, flags);
}
......

<span class="hljs-comment">// Step 3, draw the content</span>
<span class="hljs-keyword">if</span> (!dirtyOpaque) onDraw(canvas);

<span class="hljs-comment">// Step 4, draw the children</span>
dispatchDraw(canvas);

<span class="hljs-comment">// Step 5, draw the fade effect and restore layers</span>
......
<span class="hljs-keyword">if</span> (drawTop) {
matrix.setScale(<span class="hljs-number">1</span>, fadeHeight * topFadeStrength);
matrix.postTranslate(left, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
canvas.drawRect(left, top, right, top + length, p);
}
......

<span class="hljs-comment">// Step 6, draw decorations (scrollbars)</span>
onDrawScrollBars(canvas);
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li></ul>

看见整个View的draw方法很复杂,但是源码注释也很明显。从注释可以看出整个draw过程分为了6步。源码注释说(”skip step 2 & 5 if possible (common case)”)第2和5步可以跳过,所以我们接下来重点剩余四步。如下:

第一步,对View的背景进行绘制。

可以看见,draw方法通过调运drawBackground(canvas);方法实现了背景绘制。我们来看下这个方法源码,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">drawBackground</span>(Canvas canvas) {
<span class="hljs-comment">//获取xml中通过android:background属性或者代码中setBackgroundColor()、setBackgroundResource()等方法进行赋值的背景Drawable</span>
<span class="hljs-keyword">final</span> Drawable background = mBackground;
......
<span class="hljs-comment">//根据layout过程确定的View位置来设置背景的绘制区域</span>
<span class="hljs-keyword">if</span> (mBackgroundSizeChanged) {
background.setBounds(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>,  mRight - mLeft, mBottom - mTop);
mBackgroundSizeChanged = <span class="hljs-keyword">false</span>;
rebuildOutline();
}
......
<span class="hljs-comment">//调用Drawable的draw()方法来完成背景的绘制工作</span>
background.draw(canvas);
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li></ul>

第三步,对View的内容进行绘制。

可以看到,这里去调用了一下View的onDraw()方法,所以我们看下View的onDraw方法(ViewGroup也没有重写该方法),如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-javadoc">/**
* Implement this to do your drawing.
*
*<span class="hljs-javadoctag"> @param</span> canvas the canvas on which the background will be drawn
*/</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onDraw</span>(Canvas canvas) {
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li></ul>

可以看见,这是一个空方法。因为每个View的内容部分是各不相同的,所以需要由子类去实现具体逻辑。

第四步,对当前View的所有子View进行绘制,如果当前的View没有子View就不需要进行绘制。

我们来看下View的draw方法中的dispatchDraw(canvas);方法源码,可以看见如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-javadoc">/**
* Called by draw to draw the child views. This may be overridden
* by derived classes to gain control just before its children are drawn
* (but after its own view has been drawn).
*<span class="hljs-javadoctag"> @param</span> canvas the canvas on which to draw the view
*/</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dispatchDraw</span>(Canvas canvas) {

}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li></ul>

看见没有,View的dispatchDraw()方法是一个空方法,而且注释说明了如果View包含子类需要重写他,所以我们有必要看下ViewGroup的dispatchDraw方法源码(这也就是刚刚说的对当前View的所有子View进行绘制,如果当前的View没有子View就不需要进行绘制的原因,因为如果是View调运该方法是空的,而ViewGroup才有实现),如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dispatchDraw</span>(Canvas canvas) {
......
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> childrenCount = mChildrenCount;
<span class="hljs-keyword">final</span> View[] children = mChildren;
......
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i < childrenCount; i++) {
......
<span class="hljs-keyword">if</span> ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != <span class="hljs-keyword">null</span>) {
more |= drawChild(canvas, child, drawingTime);
}
}
......
<span class="hljs-comment">// Draw any disappearing views that have animations</span>
<span class="hljs-keyword">if</span> (mDisappearingChildren != <span class="hljs-keyword">null</span>) {
......
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = disappearingCount; i >= <span class="hljs-number">0</span>; i--) {
......
more |= drawChild(canvas, child, drawingTime);
}
}
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li></ul>

可以看见,ViewGroup确实重写了View的dispatchDraw()方法,该方法内部会遍历每个子View,然后调用drawChild()方法,我们可以看下ViewGroup的drawChild方法,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">protected</span> <span class="hljs-keyword">boolean</span> <span class="hljs-title">drawChild</span>(Canvas canvas, View child, <span class="hljs-keyword">long</span> drawingTime) {
<span class="hljs-keyword">return</span> child.draw(canvas, <span class="hljs-keyword">this</span>, drawingTime);
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li></ul>

可以看见drawChild()方法调运了子View的draw()方法。所以说ViewGroup类已经为我们重写了dispatchDraw()的功能实现,我们一般不需要重写该方法,但可以重载父类函数实现具体的功能。

第六步,对View的滚动条进行绘制。

可以看到,这里去调用了一下View的onDrawScrollBars()方法,所以我们看下View的onDrawScrollBars(canvas);方法,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-javadoc">/**
* <p>Request the drawing of the horizontal and the vertical scrollbar. The
* scrollbars are painted only if they have been awakened first.</p>
*
*<span class="hljs-javadoctag"> @param</span> canvas the canvas on which to draw the scrollbars
*
*<span class="hljs-javadoctag"> @see</span> #awakenScrollBars(int)
*/</span>
<span class="hljs-keyword">protected</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onDrawScrollBars</span>(Canvas canvas) {
<span class="hljs-comment">//绘制ScrollBars分析不是我们这篇的重点,所以暂时不做分析</span>
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li></ul>

可以看见其实任何一个View都是有(水平垂直)滚动条的,只是一般情况下没让它显示而已。

到此,View的draw绘制部分源码分析完毕,我们接下来进行一些总结。

4-2 draw原理总结

可以看见,绘制过程就是把View对象绘制到屏幕上,整个draw过程需要注意如下细节:

如果该View是一个ViewGroup,则需要递归绘制其所包含的所有子View。

View默认不会绘制任何内容,真正的绘制都需要自己在子类中实现。

View的绘制是借助onDraw方法传入的Canvas类来进行的。

区分View动画和ViewGroup布局动画,前者指的是View自身的动画,可以通过setAnimation添加,后者是专门针对ViewGroup显示内部子视图时设置的动画,可以在xml布局文件中对ViewGroup设置layoutAnimation属性(譬如对LinearLayout设置子View在显示时出现逐行、随机、下等显示等不同动画效果)。

在获取画布剪切区(每个View的draw中传入的Canvas)时会自动处理掉padding,子View获取Canvas不用关注这些逻辑,只用关心如何绘制即可。

默认情况下子View的ViewGroup.drawChild绘制顺序和子View被添加的顺序一致,但是你也可以重载ViewGroup.getChildDrawingOrder()方法提供不同顺序。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

5 View的invalidate和postInvalidate方法源码分析

你可能已经看见了,在上面分析View的三步绘制流程中最后都有调运一个叫invalidate的方法,这个方法是啥玩意?为何出现频率这么高?很简单,我们拿出来分析分析不就得了。

5-1 invalidate方法源码分析

来看一下View类中的一些invalidate方法(ViewGroup没有重写这些方法),如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-javadoc">/**
* Mark the area defined by dirty as needing to be drawn. If the view is
* visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
* point in the future.
* <p>
* This must be called from a UI thread. To call from a non-UI thread, call
* {@link #postInvalidate()}.
* <p>
* <b>WARNING:</b> In API 19 and below, this method may be destructive to
* {@code dirty}.
*
*<span class="hljs-javadoctag"> @param</span> dirty the rectangle representing the bounds of the dirty region
*/</span>
<span class="hljs-comment">//看见上面注释没有?public,只能在UI Thread中使用,别的Thread用postInvalidate方法,View是可见的才有效,回调onDraw方法,针对局部View</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">invalidate</span>(Rect dirty) {
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> scrollX = mScrollX;
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> scrollY = mScrollY;
<span class="hljs-comment">//实质还是调运invalidateInternal方法</span>
invalidateInternal(dirty.left - scrollX, dirty.top - scrollY,
dirty.right - scrollX, dirty.bottom - scrollY, <span class="hljs-keyword">true</span>, <span class="hljs-keyword">false</span>);
}

<span class="hljs-javadoc">/**
* Mark the area defined by the rect (l,t,r,b) as needing to be drawn. The
* coordinates of the dirty rect are relative to the view. If the view is
* visible, {@link #onDraw(android.graphics.Canvas)} will be called at some
* point in the future.
* <p>
* This must be called from a UI thread. To call from a non-UI thread, call
* {@link #postInvalidate()}.
*
*<span class="hljs-javadoctag"> @param</span> l the left position of the dirty region
*<span class="hljs-javadoctag"> @param</span> t the top position of the dirty region
*<span class="hljs-javadoctag"> @param</span> r the right position of the dirty region
*<span class="hljs-javadoctag"> @param</span> b the bottom position of the dirty region
*/</span>
<span class="hljs-comment">//看见上面注释没有?public,只能在UI Thread中使用,别的Thread用postInvalidate方法,View是可见的才有效,回调onDraw方法,针对局部View</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">invalidate</span>(<span class="hljs-keyword">int</span> l, <span class="hljs-keyword">int</span> t, <span class="hljs-keyword">int</span> r, <span class="hljs-keyword">int</span> b) {
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> scrollX = mScrollX;
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> scrollY = mScrollY;
<span class="hljs-comment">//实质还是调运invalidateInternal方法</span>
invalidateInternal(l - scrollX, t - scrollY, r - scrollX, b - scrollY, <span class="hljs-keyword">true</span>, <span class="hljs-keyword">false</span>);
}

<span class="hljs-javadoc">/**
* Invalidate the whole view. If the view is visible,
* {@link #onDraw(android.graphics.Canvas)} will be called at some point in
* the future.
* <p>
* This must be called from a UI thread. To call from a non-UI thread, call
* {@link #postInvalidate()}.
*/</span>
<span class="hljs-comment">//看见上面注释没有?public,只能在UI Thread中使用,别的Thread用postInvalidate方法,View是可见的才有效,回调onDraw方法,针对整个View</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">invalidate</span>() {
<span class="hljs-comment">//invalidate的实质还是调运invalidateInternal方法</span>
invalidate(<span class="hljs-keyword">true</span>);
}

<span class="hljs-javadoc">/**
* This is where the invalidate() work actually happens. A full invalidate()
* causes the drawing cache to be invalidated, but this function can be
* called with invalidateCache set to false to skip that invalidation step
* for cases that do not need it (for example, a component that remains at
* the same dimensions with the same content).
*
*<span class="hljs-javadoctag"> @param</span> invalidateCache Whether the drawing cache for this view should be
*            invalidated as well. This is usually true for a full
*            invalidate, but may be set to false if the View's contents or
*            dimensions have not changed.
*/</span>
<span class="hljs-comment">//看见上面注释没有?default的权限,只能在UI Thread中使用,别的Thread用postInvalidate方法,View是可见的才有效,回调onDraw方法,针对整个View</span>
<span class="hljs-keyword">void</span> invalidate(<span class="hljs-keyword">boolean</span> invalidateCache) {
<span class="hljs-comment">//实质还是调运invalidateInternal方法</span>
invalidateInternal(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, mRight - mLeft, mBottom - mTop, invalidateCache, <span class="hljs-keyword">true</span>);
}

<span class="hljs-comment">//!!!!!!看见没有,这是所有invalidate的终极调运方法!!!!!!</span>
<span class="hljs-keyword">void</span> invalidateInternal(<span class="hljs-keyword">int</span> l, <span class="hljs-keyword">int</span> t, <span class="hljs-keyword">int</span> r, <span class="hljs-keyword">int</span> b, <span class="hljs-keyword">boolean</span> invalidateCache,
<span class="hljs-keyword">boolean</span> fullInvalidate) {
......
<span class="hljs-comment">// Propagate the damage rectangle to the parent view.</span>
<span class="hljs-keyword">final</span> AttachInfo ai = mAttachInfo;
<span class="hljs-keyword">final</span> ViewParent p = mParent;
<span class="hljs-keyword">if</span> (p != <span class="hljs-keyword">null</span> && ai != <span class="hljs-keyword">null</span> && l < r && t < b) {
<span class="hljs-keyword">final</span> Rect damage = ai.mTmpInvalRect;
<span class="hljs-comment">//设置刷新区域</span>
damage.set(l, t, r, b);
<span class="hljs-comment">//传递调运Parent ViewGroup的invalidateChild方法</span>
p.invalidateChild(<span class="hljs-keyword">this</span>, damage);
}
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li><li>18</li><li>19</li><li>20</li><li>21</li><li>22</li><li>23</li><li>24</li><li>25</li><li>26</li><li>27</li><li>28</li><li>29</li><li>30</li><li>31</li><li>32</li><li>33</li><li>34</li><li>35</li><li>36</li><li>37</li><li>38</li><li>39</li><li>40</li><li>41</li><li>42</li><li>43</li><li>44</li><li>45</li><li>46</li><li>47</li><li>48</li><li>49</li><li>50</li><li>51</li><li>52</li><li>53</li><li>54</li><li>55</li><li>56</li><li>57</li><li>58</li><li>59</li><li>60</li><li>61</li><li>62</li><li>63</li><li>64</li><li>65</li><li>66</li><li>67</li><li>68</li><li>69</li><li>70</li><li>71</li><li>72</li><li>73</li><li>74</li><li>75</li><li>76</li><li>77</li><li>78</li><li>79</li><li>80</li><li>81</li><li>82</li><li>83</li><li>84</li><li>85</li><li>86</li><li>87</li><li>88</li><li>89</li><li>90</li><li>91</li><li>92</li></ul>

看见没有,View的invalidate(invalidateInternal)方法实质是将要刷新区域直接传递给了父ViewGroup的invalidateChild方法,在invalidate中,调用父View的invalidateChild,这是一个从当前向上级父View回溯的过程,每一层的父View都将自己的显示区域与传入的刷新Rect做交集 。所以我们看下ViewGroup的invalidateChild方法,源码如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">void</span> <span class="hljs-title">invalidateChild</span>(View child, <span class="hljs-keyword">final</span> Rect dirty) {
ViewParent parent = <span class="hljs-keyword">this</span>;
<span class="hljs-keyword">final</span> AttachInfo attachInfo = mAttachInfo;
......
do {
......
<span class="hljs-comment">//循环层层上级调运,直到ViewRootImpl会返回null</span>
parent = parent.invalidateChildInParent(location, dirty);
......
} <span class="hljs-keyword">while</span> (parent != <span class="hljs-keyword">null</span>);
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li></ul>

这个过程最后传递到ViewRootImpl的invalidateChildInParent方法结束,所以我们看下ViewRootImpl的invalidateChildInParent方法,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">public</span> ViewParent <span class="hljs-title">invalidateChildInParent</span>(<span class="hljs-keyword">int</span>[] location, Rect dirty) {
......
<span class="hljs-comment">//View调运invalidate最终层层上传到ViewRootImpl后最终触发了该方法</span>
scheduleTraversals();
......
<span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li></ul>

看见没有?这个ViewRootImpl类的invalidateChildInParent方法直接返回了null,也就是上面ViewGroup中说的,层层上级传递到ViewRootImpl的invalidateChildInParent方法结束了那个do while循环。看见这里调运的scheduleTraversals这个方法吗?scheduleTraversals会通过Handler的Runnable发送一个异步消息,调运doTraversal方法,然后最终调用performTraversals()执行重绘。开头背景知识介绍说过的,performTraversals就是整个View数开始绘制的起始调运地方,所以说View调运invalidate方法的实质是层层上传到父级,直到传递到ViewRootImpl后触发了scheduleTraversals方法,然后整个View树开始重新按照上面分析的View绘制流程进行重绘任务。

到此View的invalidate方法原理就分析完成了。

5-2 postInvalidate方法源码分析

上面分析invalidate方法时注释中说该方法只能在UI Thread中执行,其他线程中需要使用postInvalidate方法,所以我们来分析分析postInvalidate这个方法源码。如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">postInvalidate</span>() {
postInvalidateDelayed(<span class="hljs-number">0</span>);
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li></ul>

继续看下他的调运方法postInvalidateDelayed,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">postInvalidateDelayed</span>(<span class="hljs-keyword">long</span> delayMilliseconds) {
<span class="hljs-comment">// We try only with the AttachInfo because there's no point in invalidating</span>
<span class="hljs-comment">// if we are not attached to our window</span>
<span class="hljs-keyword">final</span> AttachInfo attachInfo = mAttachInfo;
<span class="hljs-comment">//核心,实质就是调运了ViewRootImpl.dispatchInvalidateDelayed方法</span>
<span class="hljs-keyword">if</span> (attachInfo != <span class="hljs-keyword">null</span>) {
attachInfo.mViewRootImpl.dispatchInvalidateDelayed(<span class="hljs-keyword">this</span>, delayMilliseconds);
}
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li></ul>

我们继续看他调运的ViewRootImpl类的dispatchInvalidateDelayed方法,如下源码:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">dispatchInvalidateDelayed</span>(View view, <span class="hljs-keyword">long</span> delayMilliseconds) {
Message msg = mHandler.obtainMessage(MSG_INVALIDATE, view);
mHandler.sendMessageDelayed(msg, delayMilliseconds);
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li></ul>

看见没有,通过ViewRootImpl类的Handler发送了一条MSG_INVALIDATE消息,继续追踪这条消息的处理可以发现:

<code class="language-java hljs  has-numbering"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handleMessage</span>(Message msg) {
......
<span class="hljs-keyword">switch</span> (msg.what) {
<span class="hljs-keyword">case</span> MSG_INVALIDATE:
((View) msg.obj).invalidate();
<span class="hljs-keyword">break</span>;
......
}
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li></ul>

看见没有,实质就是又在UI Thread中调运了View的invalidate();方法,那接下来View的invalidate();方法我们就不说了,上名已经分析过了。

到此整个View的postInvalidate方法就分析完成了。

5-3 invalidate与postInvalidate方法总结

依据上面对View的invalidate分析我总结绘制如下流程图:



依据上面对View的postInvalidate分析我总结绘制如下流程图:



关于这两个方法的具体流程和原理上面也分析过了,流程图也给出了,相信已经很明确了,没啥需要解释的了。所以我们对其做一个整体总结,归纳出重点如下:

invalidate系列方法请求重绘View树(也就是draw方法),如果View大小没有发生变化就不会调用layout过程,并且只绘制那些“需要重绘的”View,也就是哪个View(View只绘制该View,ViewGroup绘制整个ViewGroup)请求invalidate系列方法,就绘制该View。

常见的引起invalidate方法操作的原因主要有:

直接调用invalidate方法.请求重新draw,但只会绘制调用者本身。
触发setSelection方法。请求重新draw,但只会绘制调用者本身。
触发setVisibility方法。 当View可视状态在INVISIBLE转换VISIBLE时会间接调用invalidate方法,继而绘制该View。当View的可视状态在INVISIBLE\VISIBLE 转换为GONE状态时会间接调用requestLayout和invalidate方法,同时由于View树大小发生了变化,所以会请求measure过程以及draw过程,同样只绘制需要“重新绘制”的视图。
触发setEnabled方法。请求重新draw,但不会重新绘制任何View包括该调用者本身。
触发requestFocus方法。请求View树的draw过程,只绘制“需要重绘”的View。

5-4 通过invalidate方法分析结果回过头去解决一个背景介绍中的疑惑

分析完invalidate后需要你回过头去想一个问题。还记不记得这篇文章的开头背景介绍,我们说整个View绘制流程的最初代码是在ViewRootImpl类的performTraversals()方法中开始的。上面当时只是告诉你了这个结论,至于这个ViewRootImpl类的performTraversals()方法为何会被触发没有说明原因。现在我们就来分析一下这个触发的源头。

让我们先把大脑思考暂时挪回到《Android应用setContentView与LayoutInflater加载解析机制源码分析》这篇博文的setContentView机制分析中(不清楚的请点击先看这篇文章再回过头来继续看)。我们先来看下那篇博文分析的PhoneWindow的setContentView方法源码,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setContentView</span>(View view, ViewGroup.LayoutParams params) {
......
<span class="hljs-comment">//如果mContentParent为空进行一些初始化,实质mContentParent是通过findViewById(ID_ANDROID_CONTENT);获取的id为content的FrameLayout的布局(不清楚的请先看《Android应用setContentView与LayoutInflater加载解析机制源码分析》文章)</span>
<span class="hljs-keyword">if</span> (mContentParent == <span class="hljs-keyword">null</span>) {
installDecor();
}
......
<span class="hljs-comment">//把我们的view追加到mContentParent</span>
mContentParent.addView(view, params);
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li></ul>

这个方法是Activity中setContentView的实现,我们继续看下这个方法里调运的addView方法,也就是ViewGroup的addView方法,如下:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addView</span>(View child) {
addView(child, -<span class="hljs-number">1</span>);
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addView</span>(View child, <span class="hljs-keyword">int</span> index) {
......
addView(child, index, params);
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addView</span>(View child, <span class="hljs-keyword">int</span> index, LayoutParams params) {
......
<span class="hljs-comment">//该方法稍后后面会详细分析</span>
requestLayout();
<span class="hljs-comment">//重点关注!!!</span>
invalidate(<span class="hljs-keyword">true</span>);
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li><li>10</li><li>11</li><li>12</li><li>13</li><li>14</li><li>15</li><li>16</li><li>17</li></ul>

看见addView调运invalidate方法没有?这不就真相大白了。当我们写一个Activity时,我们一定会通过setContentView方法将我们要展示的界面传入该方法,该方法会讲我们界面通过addView追加到id为content的一个FrameLayout(ViewGroup)中,然后addView方法中通过调运invalidate(true)去通知触发ViewRootImpl类的performTraversals()方法,至此递归绘制我们自定义的所有布局。

【工匠若水 http://blog.csdn.net/yanbober 转载烦请注明出处,尊重分享成果】

6 View的requestLayout方法源码分析

6-1 requestLayout方法分析

和invalidate类似,其实在上面分析View绘制流程时或多或少都调运到了这个方法,而且这个方法对于View来说也比较重要,所以我们接下来分析一下他。如下View的requestLayout源码:

<code class="language-java hljs  has-numbering">    <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">requestLayout</span>() {
......
<span class="hljs-keyword">if</span> (mParent != <span class="hljs-keyword">null</span> && !mParent.isLayoutRequested()) {
<span class="hljs-comment">//由此向ViewParent请求布局</span>
<span class="hljs-comment">//从这个View开始向上一直requestLayout,最终到达ViewRootImpl的requestLayout</span>
mParent.requestLayout();
}
......
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li></ul>

看见没有,当我们触发View的requestLayout时其实质就是层层向上传递,直到ViewRootImpl为止,然后触发ViewRootImpl的requestLayout方法,如下就是ViewRootImpl的requestLayout方法:

<code class="language-java hljs  has-numbering">    <span class="hljs-annotation">@Override</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">requestLayout</span>() {
<span class="hljs-keyword">if</span> (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = <span class="hljs-keyword">true</span>;
<span class="hljs-comment">//View调运requestLayout最终层层上传到ViewRootImpl后最终触发了该方法</span>
scheduleTraversals();
}
}</code><ul style="display: block;" class="pre-numbering"><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li><li>7</li><li>8</li><li>9</li></ul>

看见没有,类似于上面分析的invalidate过程,只是设置的标记不同,导致对于View的绘制流程中触发的方法不同而已。

6-2 requestLayout方法总结

可以看见,这些方法都是大同小异。对于requestLayout方法来说总结如下:

requestLayout()方法会调用measure过程和layout过程,不会调用draw过程,也不会重新绘制任何View包括该调用者本身。

7 View绘制流程总结

至此整个关于Android应用程序开发中的View绘制机制及相关重要方法都已经分析完毕。关于各个方法的总结这里不再重复,直接通过该文章前面的目录索引到相应方法的总结小节进行查阅即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: