第四章 View的工作原理
知识准备
ViewRoot
- ViewRoot对应ViewRootImpl类,是连接WindowManager与DecorView的纽带。
- View的三大流程都是通过ViewRoot完成的。
- ActivityThread中,Activity对象被创建完毕时,会将DecorView添加到Window中,同时创建ViewRootImpl对象,并将ViewRootImpl对象和DecorView对象建立关联。
//创建ViewRootImpl对象root = new ViewRootImpl(view.getContext(),display);//添加关联root.setView(view,wparams,panelparentView);
View绘制流程从ViewRoot的performTraversals方法开始,经过measure、layout、draw三大流程后才将View绘制出来。performTraversals方法(8W多行代码),会依次调用performMeasure、performLayout、performDraw方法(这三个方法分别完成顶级View - DecorView 的measure、layout、draw方法)其中performMeasure方法会调用measure方法,在measure方法中又会调用onMeasure方法,onMeasure方法则会对所有子元素进行measure,从而达到measure流程从父容器传递到子元素中的目的。接着子元素会重复父容器的measure过程,如此反复完成整个View树的遍历。最后,perfromLayout、performDraw的传递过程也是类似的,唯一不同,而performDraw的传递过程在draw方法中通过dispatchDraw来实现。
MeasureSpec:
MeasureSpec代表一个32位int值,高2位代表SpecMode(测量模式),低30位代表SpecSize(规格大小)小白科普:Java中int为4个字节,Android使用第一个高位字节存储Mode,剩下三个字节存储Size
系统内部是通过MeasureSpec进行View测量的,但正常情况下,都是使View指定MeasureSpec。
View测量时候系统会将LayoutParams在父容器约束下转换成对应的MeasureSpec,然后再根据这个MeasureSpec来确定View测量后的宽高。因此,Measure需要由LayoutParams和父容器一起决定。
View测量时候系统会将LayoutParams在父容器约束下转换成对应的MeasureSpec,然后再根据这个MeasureSpec来确定View测量后的宽高。因此,Measure需要由LayoutParams和父容器一起决定。
另外,对于顶级View(DecorView),其MeasureSpec由窗口尺寸和其自身的LayoutParams共同决定。Measure一旦决定后,onMeasure中即可获得View的测量宽高。
以下是DecorView获得MeasureSpec的过程:
其中rootDimension是DecorView的LayoutParam指定的宽高。
/*** DecorView中,MeasureSpec产生过程* 根据LayoutParams划分,并产生MeasureSpec*/private static int getRootMeasureSpec(int windowSize, int rootDimension) {int measureSpec;switch (rootDimension) {case ViewGroup.LayoutParams.MATCH_PARENT:// Window can't resize. Force root view to be windowSize.measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);break;case ViewGroup.LayoutParams.WRAP_CONTENT:// Window can resize. Set max size for root view.measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);break;default:// Window wants to be an exact size. Force root view to be that size.measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);break;}return measureSpec;}
上述代码很明确的可以看出DecorView的SpecMeasure的创建过程,如果是MATCH_PARENT那它的大小就是当前窗口的大小,
如果是WRAP_CONTENT:最大模式,大小是不定的,但是最大不能超过windowSize。
我们关心的是普通的View的绘制过程。下面就来分析一下普通View的measure过程:
对于普通View(布局中的View),View的measure方法需要由ViewGroup传递过来所以我们先看看ViewGroup中的measureChildWithMargins方法
protected void measureChildWithMargins(View child,int parentWidthMeasureSpec, int widthUsed,int parentHeightMeasureSpec, int heightUsed) {final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();- final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin+ widthUsed, lp.width);final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin+ heightUsed, lp.height);child.measure(childWidthMeasureSpec, childHeightMeasureSpec);}
很明显,childMeasureSpec的值和父容器的MeasureSpec和自身的LayoutParam,以及自身的padding,margin相关。
从这一行中可以很明显的看出
- final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin+ widthUsed, lp.width);
那到底是如何使用协调这些参数的呢? 其具体情况可以看一下getChildMeasureSpec的实现
代码如下:
先解释一下padding其实是父容器已经占用了的空间,很明显其就是所设置的子view padding和margin的和。
则第五行这个size就是父容器剩下可以使用的size。
在Switch代码中可以看到子view的MeasureSpec是由ViewGroup的MODEL和子View的LayoutParams共同决定的。
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {int specMode = MeasureSpec.getMode(spec);int specSize = MeasureSpec.getSize(spec);int size = Math.max(0, specSize - padding);int resultSize = 0;int resultMode = 0;switch (specMode) {// Parent has imposed an exact size on uscase MeasureSpec.EXACTLY:if (childDimension >= 0) {resultSize = childDimension;resultMode = MeasureSpec.EXACTLY;} else if (childDimension == LayoutParams.MATCH_PARENT) {// Child wants to be our size. So be it.resultSize = size;resultMode = MeasureSpec.EXACTLY;} else if (childDimension == LayoutParams.WRAP_CONTENT) {// Child wants to determine its own size. It can't be// bigger than us.resultSize = size;resultMode = MeasureSpec.AT_MOST;}break;// Parent has imposed a maximum size on uscase MeasureSpec.AT_MOST:if (childDimension >= 0) {// Child wants a specific size... so be itresultSize = childDimension;resultMode = MeasureSpec.EXACTLY;} else if (childDimension == LayoutParams.MATCH_PARENT) {// Child wants to be our size, but our size is not fixed.// Constrain child to not be bigger than us.resultSize = size;resultMode = MeasureSpec.AT_MOST;} else if (childDimension == LayoutParams.WRAP_CONTENT) {// Child wants to determine its own size. It can't be// bigger than us.resultSize = size;resultMode = MeasureSpec.AT_MOST;}break;// Parent asked to see how big we want to becase MeasureSpec.UNSPECIFIED:if (childDimension >= 0) {// Child wants a specific size... let him have itresultSize = childDimension;resultMode = MeasureSpec.EXACTLY;} else if (childDimension == LayoutParams.MATCH_PARENT) {// Child wants to be our size... find out how big it should// beresultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;resultMode = MeasureSpec.UNSPECIFIED;} else if (childDimension == LayoutParams.WRAP_CONTENT) {// Child wants to determine its own size.... find out how// big it should beresultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;resultMode = MeasureSpec.UNSPECIFIED;}break;}return MeasureSpec.makeMeasureSpec(resultSize, resultMode);}
这个是上面这段代码的总结图:

表格中parentSize就是代码里的size也就是父容器目前可用的Size。
接下来的分析情况下文
View的工作过程:
主要流程是measure、layout、draw这三大过程。
- measure 确定View宽高
- layout确定View最终宽高和四个顶点位置
- draw将View绘制到屏幕
我们继续上面的measure。
探究Measure过程
- 两种情况,若只是一个原始的View,通过measure方法就完成了测量过程;如果是ViewGroup,除了完成自身的measure过程,还需要遍历子元素的measure方法,各个子元素递归去执行这个部分。
- View的measure方法是一个final类型的方法 - 意味着子类不能重写该方法,因此仔细研究onMeasure方法的实现效果会更好。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));}
setMeasuredDimension 方法会设置view宽高的测量值,因此我们只需看getDefaultSize就行了。
public static int getDefaultSize(int size, int measureSpec) {int result = size;int specMode = MeasureSpec.getMode(measureSpec);int specSize = MeasureSpec.getSize(measureSpec);switch (specMode) {case MeasureSpec.UNSPECIFIED://一般是系统内部的测量过程,重点注意另外两种模式result = size;break;case MeasureSpec.AT_MOST://这两种模式都是做一样的事情case MeasureSpec.EXACTLY:result = specSize;break;}return result;}
getDefaultSize方法直接就是根据测量模式返回measureSpec中的specSize,而这个specSize就是View测量后的大小。注意:View测量后大小 与 View最终大小 需要区分,是两个东西,因为View最终大小是在layout阶段确定的,但两者几乎所有情况都是相等的。
接下来,再继续探究getDefaultSize方法的第一个参数,从onMeasure方法中可知,该参数来源于下面两个方法protected int getSuggestedMinimumWidth() {return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());}protected int getSuggestedMinimumHeight() {return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());}上述两个方法实现原理都一致,判断有没有背景,如果有,返回两者较大的宽高,没有则返回自己的宽高(android:minwith这个属性指定的值)。那么,问题来了,背景最小宽高原理是什么?public int getMinimumWidth() {final int intrinsicWidth = getIntrinsicWidth();return intrinsicWidth > 0 ? intrinsicWidth : 0;}上述代码中可见,Drawable的原始宽度,如果没有原始宽度,则返回0。小白科普:ShapeDrawable无原始宽高,而BimapDrawable有原始宽高(即图片尺寸)
通过上面的分析,我们是不是发现了一个问题:既WRAP_CONTENT是不是起不到warp_content的作用?
我们看,View的绘制和其LayoutParam与父容器的MeasureSpec有关,查看那张表,我们看到当view设定为Wrap_content的时候,其View的Measure MODEL为 AT_MOST,其size为parentsize(也就是父容器可用的sieze)。也就是说onMeasure方法中得到的测量大小其实和match_parent没有任何区别(都是parentsize)
其实解决也很简单
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);if (widthSpecMode == MeasureSpec.AT_MOST&& heightSpecMode == MeasureSpec.AT_MOST) {setMeasuredDimension(200, 200);} else if (widthSpecMode == MeasureSpec.AT_MOST) {setMeasuredDimension(200, heightSpecSize);} else if (heightSpecMode == MeasureSpec.AT_MOST) {setMeasuredDimension(widthSpecSize, 200);}}
对于Wrap_cont的我们自己指定一个height或者weight即可,当然这个宽高要自己算。
再谈谈ViewGroup的measure过程与上面的主要区别:1. 除了完成自己measure过程还要遍历调用子元素的measure方法,各个子元素再递归执行该过程。2. ViewGroup是抽象类,没有重写View的onMeasure方法,而是提供了一个measureChildren的方法
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {final int size = mChildrenCount;final View[] children = mChildren;for (int i = 0; i < size; ++i) {final View child = children[i];if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {measureChild(child, widthMeasureSpec, heightMeasureSpec);}}}protected void measureChild(View child, int parentWidthMeasureSpec,int parentHeightMeasureSpec) {final LayoutParams lp = child.getLayoutParams();final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,mPaddingLeft + mPaddingRight, lp.width);final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,mPaddingTop + mPaddingBottom, lp.height);child.measure(childWidthMeasureSpec, childHeightMeasureSpec);}View在measure过程中会对每一个子元素进行measure。
再细说下,measureChild方法的思路:
1. 取出子元素的LayoutParams
2. 通过getChildMeasureSpec创建子元素的MeasureSpec
3. 将MeasureSpec传递给View的Measure方法进行测量。问题:为什么ViewGroup不像View一样对其onMeasure方法做统一实现?
因为不同的ViewGroup子类会有不同的特性,因此其中的onMeasure细节不相同。
引申:
获取View宽高方法不当,可能会获取错误。
原因:View的measure过程和Activity生命周期方法执行顺序是不确定的,无法保证Activity执行了onCreate、onStart、onReasume时,View测量完毕。
如果View还没有完成测量,则获取的宽高会是0.
原因:View的measure过程和Activity生命周期方法执行顺序是不确定的,无法保证Activity执行了onCreate、onStart、onReasume时,View测量完毕。
如果View还没有完成测量,则获取的宽高会是0.
给出四种方法解决:
1、onWindowFocusChanged - 该方法被调用时候,View已经测量完毕,能够正确获取View宽高。
注意:该方法会被调用多次,Activity窗口得到焦点与失去焦点时均会被调用一次(继续执行,暂停执行)。
public void onWindowFocusChanged(boolean hasWindowFocus) {super.onWindowFocusChanged(hasWindowFocus);if(hasWindowFocus){//获取宽高int with = view.getMeasuredWidth();int height = view.getMeasuredHeight();}}
2、view.post(runnable)
通过post将一个runnable投递到消息队列队尾,等待Looper调用此runnable时,View已初始化完毕。
protected void onStart(){super.onStart();view.post(new Runnable(){@overridepublic void run(){//获取宽高int with = view.getMeasuredWidth();int height = view.getMeasuredHeight();}})}
3、ViewTreeObserver 该类有众多回调接口,其中的OnGlobalLayoutListener接口,当View树状态发生变化或者View树内部的View的可见性发生改变,该方法都会被回调,利用此特性,可获得宽高。
protected void onStart(){super.onStart();viewTreeObserver observer = view.getViewTreeObserver();observer.addOnGlobalLayoutListener(new OnGlobalListener(){public void onGlobalLayout(){view.getViewTreeObserver().removeGlobalOnlayoutListener(this);//获取宽高int with = view.getMeasuredWidth();int height = view.getMeasuredHeight();}})}
view.measure(int widthMeasureSpec,int heightMeasureSpec)手动对View进行获取,根据View的LayoutParams不同,而采取不同手段。(因不常用,这里就不详细说明)
4、view.measure(int widthMeasureSpec,int heightMeasureSpec) 手动对View进行获取,根据View的LayoutParams不同,而采取不同手段。(因不常用,这里就不详细说明)
layout过程:
public void layout(int l, int t, int r, int b) {if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;}//设定四个顶点位置int oldL = mLeft;int oldT = mTop;int oldB = mBottom;int oldR = mRight;boolean changed = isLayoutModeOptical(mParent) ?setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {onLayout(changed, l, t, r, b);mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;ListenerInfo li = mListenerInfo;if (li != null && li.mOnLayoutChangeListeners != null) {ArrayList<OnLayoutChangeListener> listenersCopy =(ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();int numListeners = listenersCopy.size();for (int i = 0; i < numListeners; ++i) {listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);}}}mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;}
1. setFrame方法设定View四个顶点位置
2. 调用onLayout方法,父容器确定子元素位置
另外,与onMeasure方法相似,onLayout方法也是各不相同的。
2. 调用onLayout方法,父容器确定子元素位置
另外,与onMeasure方法相似,onLayout方法也是各不相同的。
draw过程:
draw主要作用是将View绘制到屏幕上
绘制过程: 1. 绘制背景(background.draw(canvas))2. 绘制自己(onDraw)3. 绘制children(dispatchDraw)4. 绘制装饰(onDrawScrollBars)
View的绘制过程传递是通过dispatchDraw来实现,dispatchDraw会遍历所有子元素的draw方法,另外,View还有一个特殊的方法setWillNotDrawpublic void setWillNotDraw(boolean willNotDraw) {setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);}setFlags - 该方法可设置优化标记如果View不需要绘制任何内容,那么将设置标记为true,系统会相应优化。默认情况下,View不启用这个标记位,但ViewGroup会默认启动该优化标记。而实际开发意义:当我们自定义控件继承于ViewGroup并且本身不具备绘制功能,则开启标记。而如果明确知道一个ViewGroup需要通过onDraw来绘制内容时候,则需要显式关闭WILL_NOT_DRAW这个标记位。
下面的流程图便于方便理解View的工作过程


自定义VIEW:
1. 分类:
- 继承View从写onDraw()方法
采用这种方式需要自己支持wrap_content,并且padding也需要自己处理。 - 继承ViewGroup派生特殊的Layout
当效果看起来很像集中View组合在一起的时候,可以采用这种方法来实现。 - 继承特定的View
一般用于扩展某种已有的View的功能。比如继承TextView进行增强等。 - 继承特定的ViewGroup
比如继承LinearLayout进行增强等,或者继承RelativeLayout写组合控件。
2. 自定义View注意事项:
- 让View支持wrap_content
直接继承View或ViewGroup的控件,如果不支持wrap_content,则该控件的表现效果和match_parent一样。 - 如果有必要,支持padding
直接继承View的控件,不在draw()方法中处理padding,则padding属性失效。继承ViewGroup的控件必须要在onMeasure()和onLayout()中考虑padding和margin,否则这两属性失效。 - 尽量不要在View中使用Handler
View本身就提供了post系列方法,完全可以替代handler。除非很明确地要使用handler。 - View中如果有线程或动画,需要及时停止
在View.onDetachedFromWindow()中停止。如果不及时处理,会造成内存溢出。当包含此View的Activity退出或者此View被remove()时,就会调用该方法。 - View带有滑动嵌套情形时,需要处理好滑动冲突
举一个很简单的例子:
package com.ryg.chapter_4.ui;import com.ryg.chapter_4.R;import android.content.Context;import android.content.res.TypedArray;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.View;public class CircleView extends View {private int mColor = Color.RED;private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);public CircleView(Context context) {super(context);init();}public CircleView(Context context, AttributeSet attrs) {this(context, attrs, 0);}public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);a.recycle();init();}private void init() {mPaint.setColor(mColor);}@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure(widthMeasureSpec, heightMeasureSpec);int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);if (widthSpecMode == MeasureSpec.AT_MOST&& heightSpecMode == MeasureSpec.AT_MOST) {setMeasuredDimension(200, 200);} else if (widthSpecMode == MeasureSpec.AT_MOST) {setMeasuredDimension(200, heightSpecSize);} else if (heightSpecMode == MeasureSpec.AT_MOST) {setMeasuredDimension(widthSpecSize, 200);}}@Overrideprotected void onDraw(Canvas canvas) {super.onDraw(canvas);final int paddingLeft = getPaddingLeft();final int paddingRight = getPaddingLeft();final int paddingTop = getPaddingLeft();final int paddingBottom = getPaddingLeft();int width = getWidth() - paddingLeft - paddingRight;int height = getHeight() - paddingTop - paddingBottom;int radius = Math.min(width, height) / 2;canvas.drawCircle(paddingLeft + width / 2, paddingTop + height / 2,radius, mPaint);}}
如何定义属性呢?
1、新建一个xml用来配置属性:
<?xml version="1.0" encoding="utf-8"?><resources><declare-styleable name="CircleView"><attr name="circle_color" format="color" /></declare-styleable></resources>
<declare-styleable name="CircleView"> 这句表示自定义一个属性集合“CircleView”
2、在View的构造方法中解析自定义属性的值并作出相应处理。
public CircleView(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CircleView);mColor = a.getColor(R.styleable.CircleView_circle_color, Color.RED);a.recycle();init();}
更详细的例子:
待补。。。 好困

浙公网安备 33010602011771号