4源码的角度分析View
内容:View的三大工作流程源码分析
measure过程
1.View的measure过程
- 由measure方法来完成,该方法是静态的不能被子类重写,在view的measure中会调用onMeasure:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
setMeasuredDimension方法设置宽高的测量值,看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;
}
EXACTLY情况:getDefaultSize返回的大小就是MeasureSpec中的specSize,这个specSize就是测量后的大小。
UNSPECIFIED情况:view的大小为size,即宽高分别为getSuggestedMinimumWidth和getSuggestedMinimumHeight的返回值
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
protected int getSuggestedMinimumHeight() {
return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
}
可以看出,如果view没有设置背景,那么view的宽度为mMinWidth,mMinWidth 对应于android:minWidth属性所指的值,
不指定默认为0。如果view指定背景,则view的宽度为max(mMinWidth, mBackground.getMinimumWidth()),看下getMinimumWidth()方法
public int getMinimumWidth() {
final int intrinsicWidth = getIntrinsicWidth();
return intrinsicWidth > 0 ? intrinsicWidth : 0;
}
getMinimumWidth()返回的就是Drawable的原始宽度,没有原始宽度则为0,例:ShapeDrawable无原始宽度,BitmapDrawable有。
- 总结:从getDefaultSize方法中来看,View的宽高由specSize决定。
结论:直接继承View的自定义控件需要重写onMeasure方法并设置wrap_content时的自身大小,否则wrap_content效果为match_parent。
原因:结合上述代码和表4-1理解,上述代码中可知view在代码中使用wrap_content,那么specMode是AT_MOST模式,宽高等于
specSize;差表4-1可知,这种情况specSize是parentSize,而parentSize是父容器中可以使用的大小,match_parent效果一致。
解决:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSpaceSize = MeasureSpec.getSize(heightMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
if ((widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
setMeasuredDimension(mWidth,mHeight);
}else if (heightSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSpaceSize, mHeight);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(mWidth, heightSpaceSize);
} else {
}
}
在代码中只需要给view指定一个默认的内部宽高(mWidth,mHeight),并在wrap_content时设置即可,对于非wrap_content沿用系统的测量值即可。(可参考TextView,imageView源码)
2.ViewGroup的measure过程
- 对于ViewGroup除了完成自己的measure过程外,还会调用所有子元素的measure方法,各个子元素再递归去执行这个过程。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);
}
}
}
ViewGroup在measure时,会对每一个子元素进行measure,measureChild方法:
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);
}
measureChild思想是取出子元素的LayoutParams,然后再通过getChildMeasureSpec来创建子元素的MeasureSpec,接着将MeasureSpec直接传递给View的measure方法来进行测量。
- 下面通过LinearLayout的onMeasure方法来分析ViewGroup的measure过程。
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
看下measureVertical方法:由于有300行代码所以只看核心
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
measureChildBeforeLayout(child, i, widthMeasureSpec, 0,heightMeasureSpec, usedHeight);
final int childHeight = child.getMeasuredHeight();
final int totalLength = mTotalLength;
mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
lp.bottomMargin + getNextLocationOffset(child));
}
}
系统会遍历子元素并对每个子元素执行measureChildBeforeLayout方法,这个方法内部会调用measure方法,各个元素依次进入measure过程,系统会通过mTotalLength来存储LinearLayout在竖直方向的初步高度。每测量一个子元素mTotalLength都会增加,增加的部分主要包括了子元素的高度以及子元素在竖直方向上的margin等.当子元素测量完毕后,LinearLayout测量自己的大小:
// Add in our padding
mTotalLength += mPaddingTop + mPaddingBottom;
int heightSize = mTotalLength;
// Check against our minimum height
heightSize = Math.max(heightSize, getSuggestedMinimumHeight());
// Reconcile our calculated size with the heightMeasureSpec
int heightSizeAndState = resolveSizeAndState(heightSize, heightMeasureSpec, 0);
heightSize = heightSizeAndState & MEASURED_SIZE_MASK;
···
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
对竖直LinearLayout而言,它在水平方向的测量过程遵循View的测量过程,在竖直方向的测量过程则和view不同。如果它的布局中高度采用的是mathch_parent或者具体数值,那么它的测量过程与view一致,即高度为specSize;如果它的布局中高度采用wrap_content,那么它的高度是所有子元素所占的高度总和,但是仍然不能超过父容器的剩余空间,它的最终高度还需要考虑其在竖直方向的padding,看源码:
public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
final int specMode = MeasureSpec.getMode(measureSpec);
final int specSize = MeasureSpec.getSize(measureSpec);
final int result;
switch (specMode) {
case MeasureSpec.AT_MOST:
if (specSize < size) {
result = specSize | MEASURED_STATE_TOO_SMALL;
} else {
result = size;
}
break;
case MeasureSpec.EXACTLY:
result = specSize;
break;
case MeasureSpec.UNSPECIFIED:
default:
result = size;
}
return result | (childMeasuredState & MEASURED_STATE_MASK);
}
measure完成后,通过getMeasureWidth/Heigth获取测量高度。在极端情况下系统多次measure才能确定最终高度,这种情况在onMeasure方法中拿到的测量宽高不准确。好的习惯是在onLayout方法中获得View的测量宽高或最终宽高。
- 一种情况:在Activity已启动的时候就做一件任务,任务需要获取某个View的宽高。
View的measure过程和Activity的生命周期方法不是同步执行,无法保证Activity执行了onCreate、onStart、onResume时View已经测量完毕,如果View还没有测量完毕,那么获得的宽高就是0。
四种解决办法:
(1)Activity/View#onWindowFocusChanged
onWindowFocusChanged方法含义:View已经初始化完毕,宽高已经准备好了,这时候获取宽高没有问题。注意:当Activty继续执行和暂停执行时,onWindowFocusChanged均会被调用,如果频繁的进行onResume和onPause,那么onWindowFocusChanged也会被频繁的调用。代码:
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus){
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
}
(2)view.post(runnable)
通过post可以将一个runnable投递到消息队列尾部,然后等待Looper调用此runnable的时候,View也已经初始化好了,代码:
protected void onStart() {
super.onStart();
view.post(new Runnable() {
@Override
public void run() {
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
}
(3)VeiwTreeObserver
使用VeiwTreeObserver的众多回调可以完成这个功能,比如使用
OnGlobalLayoutListener接口,当View树的状态发生改变或者View树内部的View的可见性发生改变时,onGlobalLayout方法将被回调,此时获取View的宽高。注意:伴随view树的状态改变,onGlobalLayout会被调用多次。
protected void onStart() {
super.onStart();
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@SuppressWarnings("deprecation")
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
int width = view.getMeasuredWidth();
int height = view.getMeasuredHeight();
}
});
}
(4)view.measure(int widthMeasureSpec, int heightMeasureSpec)
手动对View进行measure来得到View的宽高。根据View的LayoutParams分情况处理:
- match_parent
无法measure出具体宽高。 - 具体的数值(dp/px)
比如宽高都是100px:
private void measureView() {
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
view.measure(widthMeasureSpec, heightMeasureSpec);
}
- wrap_content
private void measureView() {
int widthMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec((1 << 30) - 1, MeasureSpec.AT_MOST);
view.measure(widthMeasureSpec, heightMeasureSpec);
}
注意:(1 << 30) - 1通过分析MeasureSpec的实现可以知道,View的尺寸使用30位二进制表示,最大是30个1(即2^30-1),也就是(1 << 30) - 1,在最大化模式下,我们用View理论上能支持的最大值去构造MeasureSpec是合理的。
- 关于View的measure的错误用法:原因是违背系统内部实现规范导致measure过程出错,从而结果不能保证是正确的,错误代码:
private void measureView() {
int widthMeasureSpec = MeasureSpec.makeMeasureSpec( - 1, MeasureSpec.UNSPECIFIED);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(-1, MeasureSpec.UNSPECIFIED);
view.measure(widthMeasureSpec, heightMeasureSpec);
}
view.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout过程
作用是ViewGroup用来确定子元素的位置,确定后它在onLayout中遍历所有子元素并调用其layout方法,在layout方法中onLayout方法又被调用。
- layout方法确定View本身的位置,onLayout确定所有子元素的位置,view的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;
}
首先通过setFrame方法设定view的四个顶点的位置,即初始化 mLeft、mTop、mBottom、mRight四值,确定view在父容器中的位置;接着调用onLayout方法,这个方法的用途是父容器确定子元素的位置,实现与具体布局有关,所以View和ViewGroup没有真正实现onLayout方法。
- 看下LinearLayout的onLayout方法:
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (mOrientation == VERTICAL) {
layoutVertical(l, t, r, b);
} else {
layoutHorizontal(l, t, r, b);
}
}
layoutVertical部分代码:
void layoutVertical(int left, int top, int right, int bottom) {
···
final int count = getVirtualChildCount();
···
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child == null) {
childTop += measureNullChild(i);
} else if (child.getVisibility() != GONE) {
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
final LinearLayout.LayoutParams lp =
(LinearLayout.LayoutParams) child.getLayoutParams();
···
if (hasDividerBeforeChildAt(i)) {
childTop += mDividerHeight;
}
childTop += lp.topMargin;
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
setChildFrame中的Width和Height实际上就是子元素的测量宽高,
此方法会遍历所有子元素并调用setChildFrame方法为子元素指定对应位置,childTop会逐渐增大,子元素放在靠下位置。
setChildFrame调用子元素的layout方法,父元素在layout方法中完成自己的定位后,通过onLayout方法调用子元素的layout方法,子元素又会通过自己的layout方法来确定自己的位置,这样一层层传递下去就完成了整个View树的layout过程。
setChildFrame方法:
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
在layout方法中会通过setFrame去设置子元素的四个顶点的位置,在setFrame中有几句赋值语句,这样子元素的位置就确定了
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
- 问题:View的测量宽高与最终宽高的区别?
问题具体为:View的getMeasuredWidth和getWidth这两种方法有什么区别。
首先看getWidth和getHeight的方法实现:
public final int getWidth() {
return mRight - mLeft;
}
public final int getHeight() {
return mBottom - mTop;
}
getWidth方法返回的是View的测量宽度。
答案:在View的默认实现中,View的测量宽高和最终宽高是相等的,区别在于测量宽高形成于View的measure过程,而最终宽高形成于View的layout过程,测量宽高的赋值时机稍微早一些。
在日常开发中可以认为View的测量宽高等于最终宽高,特殊情况下才会不同。
draw过程
View的绘制过程遵循如下几步:
- 绘制背景background.draw(canvas).
- 绘制自己(onDraw).
- 绘制children(dispatchaDraw).
- 绘制装饰(onDrawScrollBars)
源码:
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
(mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
/*
* 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)
*/
// Step 1, draw the background, if needed
int saveCount;
if (!dirtyOpaque) {
drawBackground(canvas);
}
// skip step 2 & 5 if possible (common case)
final int viewFlags = mViewFlags;
boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
if (!verticalEdges && !horizontalEdges) {
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Overlay is part of the content and draws beneath Foreground
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
// we're done...
return;
}
···
}
View绘制过程的传递是通过dispatchDraw来实现,dispatchDraw会遍历调用所有子元素的draw方法,draw事件就一层层传递下去。看下View的setWillNotDraw源码:
/**
* If this view doesn't do any drawing on its own, set this flag to
* allow further optimizations. By default, this flag is not set on
* View, but could be set on some View subclasses such as ViewGroup.
*
* Typically, if you override {@link #onDraw(android.graphics.Canvas)}
* you should clear this flag.
*
* @param willNotDraw whether or not this View draw on its own
*/
public void setWillNotDraw(boolean willNotDraw) {
setFlags(willNotDraw ? WILL_NOT_DRAW : 0, DRAW_MASK);
}
注释中可以看出,如果一个view中不需要绘制任何内容,那么设置这个标记位为true以后,系统会进行相应的优化。
默认情况下view没有启动这个默认标记位,但是ViewGroup会默认启动这个优化标记位。
实际开发的意义:当我们的自定义控件继承ViewGroup并且本身不具备绘制功能时,就可以开启这个标记位便于系统进行后续的优化。当明确知道一个ViewGroup需要通过onDraw来绘制内容时,我们需要显示的关闭WILL_NOT_DRAW这个标记位。