通过前积累,我们知道了performTraversals依次调用performMeasure、performLayout、performDraw方法,最终会调用顶级View的measure,layout,draw。那么这几个方法是怎么一步步传递到我们的view当中?
通过前面介绍顶级View就是decorview,为一个FrameLayout。一般情况下里面是一个LinearLayout,这个LinearLayout又包含两个FrameLayout,分别显示标题和内容,其内容就是我们的setContentView。
其实这个问题就可以简化为measure,layout方法如何在FrameLayout传递到LinearLayout再传递到我们的View?
这里先说结论,通过源码我们可以看到FrameLayout的measure会调用onMeasure,onMeasure里面会测量自身并遍历子元素,调用子元素的measure方法测量子View。所以就调用到了LinearLayout的meausre方法,而LinearLayout.measure()又会调用LinearLayout.onMeasure方法,再其onMeasure里面又会测量自身并遍历子元素调用子元素的measure方法。这样measure方法就从顶级View传递到了我们的View,对于layout基本也是这个过程。
本文从ViewGroup和View两个角度去查看源码,先给出一些重要结论,带着结论去看源码并思考。
对于ViewGroup其measure和layout为final型,不可重写。它们分别调用了onMasure和onLayout方法。在layout调用onLayout方法的时候还完成了自身位置计算。
- 自定义ViewGroup,重写的onMeasure做两件事情,一是测量自身,二是遍历子View测量子元素。测量子元素根据实际情况调用不同方法,一般调用系统的方法比measureChildWithMargins,measureChild,如果子元素是ViewTree的最后一层也可调用view.measure
- 自定义ViewGroup,重写的onlayout,主要完成一件事子元素位置的计算
一 measrue过程
1.1View的measure过程
View的measure的方法调用流程图:
可以看到measure会调用onMeasure,其源码很简单根据传入宽高规格计算测量尺寸:
class:View
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
getDefaultSize返回View测量后的大小,注意只是测量后,不是最终大小,最终大小在layout阶段确定。大多数情况下View的测量大小和最终大小是相等的。
class:View
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;
}
主要查看AT_MOST和EXACTLY,在该两种情况下,返回的均为传入的specSize。不知是否还记得上篇文章当中最终确定child的测量模式和大小的那张表格(ViewGroup当中计算出的测量模式和大小被封装为测量规格measureSpec传入到getDefaultSize方法当中)
可以看到在父控件测量模式为AT_MOST和EXACTLY两种情况下,最终返回的子View的测量模式都是AT_MOST和EXACTLY,测量大小都是parentSize。被传入的子View,通过getDefaultSize方法计算后,返回尺寸都是specSize也就是parentSize。也就是无论子View的大小是自适应或者占满父控件其返回的测量大小都是parentSize,只有在子View确定尺寸时才会返回childSize。这也是我们继承View的自定义控件重写onMeasure方法设置wrap_content时其效果是match_parent的原因。
如何解决,可以自己定义一个宽高重写onMeasure
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int heightSize = 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(widthSize, mHeight);
} else if (widthSpecMode == MeasureSpec.AT_MOST) {
setMeasuredDimension(mWidth, heightSize);
}
}
看看上述getDefaultSize的测量规格传入UNSPECIFIED时(该情况一般系统内部测量可忽略)
这个时候getDefaultSize返回的是传入的size,那么传入的size是通过getSuggestedMinimumWidth方法获得的(高同理)。
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
总结起来就是:如果View没有设置背景,返回android:min:width(可以为0)
如果设置了背景,返回android:min:width和背景的最小宽度两者的最大值。
以上就是View的测量过程,根据传入的宽高测量规格,调用onMeasure计算尺寸。
1.2 ViewGroup的measure过程
ViewGroup为一个抽象类其并没有重写onMeasure方法,没有具体的测量自身尺寸和测量子元素的过程。那么在哪里测量呢?一般是具体的实现类重写onMeasure方法,在里面进行测量。ViewGroup提供了一些测量子元素的方法,这些方法在具体实现类的onMeasure当中根据实际情况调用。
我们先查看ViewGroup当中测量子元素方法的源码:
class:ViewGroup
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);
}
测量子元素方法的具体逻辑就是遍历子元素,通过子元素的LayoutParams和自身的measureSpec计算出子元素的测量规格(前文已提到如何计算),然后再调用子View的measure,让每个子元素去计算自己的尺寸。
那么我们思考一个问题,onMeasure方法是空的,里面为何既没测量自己也没有调用测量子元素的方法测量子View?
因为不知道具体怎么计算。比如LinearLayout就是一个ViewGroup,RelativeLayout也是一个ViewGroup,那么ViewGroup怎么知道自己该有多宽多高呢,对于竖直的LinearLayout其高度是所有的子View高度相加,对于RelativeLayout又不是这么计算。所以计算交给其具体的实现类去计算。
下面我们通过LinearLayout的源码查看其计算过程。
思考下:如果我们来写这个计算,应该如何写呢?大致思路:是不是先看LinearLayout是横向还是竖向的,如果是竖向的其宽由子元素的宽决定,高是子元素的高之和?(当然有很多限制条件比如不应大于其父容器的剩余空间,LinearLayout是match_parent还是wrap_content等)
我们来看其源码:
class: LinearLayout
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
竖直的进入measureVertical,由于measureVertical源码很多我们截取重要的查看
//class:LinearLayout measureVertical方法
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
final int usedHeight = totalWeight == 0 ? mTotalLength : 0;
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));
}
通过for循环遍历子View,通过mTotalLength记录LinearLayout在竖直方向的初步高度,测量一次mTotalLength就增加子元素的高度以及子元素在竖直方向上的margin等。
再回忆下,ViewGroup继承View,测量一开始是performTraversals调用measure,然后measure调用onMeasure。对于onMeasure的方法交由具体的实现类去完成,一般是测量自身和遍历测量子元素。这里的measureChildBeforeLayout正是去测量子元素。
当测量子元素完成后,会继续测量自己的大小,继续看LinearLayout的onMeasure源码
// 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;
...
maxWidth += mPaddingLeft + mPaddingRight;
// Check against our minimum width
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
对于上述代码进行说明,需要结合resolveSizeAndState方法查看。
在水平方向测量过程遵循View的测量过程。
竖直方向,如果采用match_parent或者精确值,测量过程和View一样高度为specSize。
竖直方向,如果采用warp_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);
}
以上就是LinearLayout的测量过程。
思考如何获得View的宽高?
在Activity生命周期做监听,调用View.getMeasureWidth()?遗憾的是这样不能实现,View绘制完成的时间和Activity的生命周期并没有关联,可以使用runnable,ViewTreeObserver,onWindowFocusChanged来做。这里列举postrunnable的方式:
@Override
protected void onStart() {
super.onStart();
view.post(new Runnable() {
@Override
public void run() {
int width = view.getMeasuredWidth();
}
});
}
二 layout过程
measure已经测量出View的尺寸了,那么View应该放在屏幕上的什么地方呢?这就需要layout来确定了。
两个方法:
- layout 确定本身位置,并调用onLayout方法确定子元素位置
- onLayout 确定所有子元素的位置
查看ViewGroup的layout方法,发现其layout方法是final型,方法体没有做太多事情,其确定位置是父类View的layout方法确定的。
下面进入View的layout方法(一定要分清ViewGroup本身也是View,layout确定View本身位置,onLayout确定它下面子元素位置)
class View:
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);
if (shouldDrawRoundScrollbar()) {
if(mRoundScrollbarRenderer == null) {
mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
}
} else {
mRoundScrollbarRenderer = null;
}
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);
}
}
}
final boolean wasLayoutValid = isLayoutValid();
mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
//.......省略
}
layout大致流程:通过setFrame方法设置View四个顶点从而确定自身的位置,调用onLayout方法测量子元素位置。
我们通过源码发现onLayout具体实现为空,和具体布局有关。
还是以LinearLayout为例
我们首先思考其onLayout方法是确定其子元素的位置的,那么就要确定全部子元素位置(子,孙,曾孙…)。是不是要一层层的全部去遍历呢?系统没有这样做,它只遍历一层。是如何做到的?如果我们在onLayout中调用一下layout方法是不是就可以达到,也就是说我们遍历第一层子元素的时候调用一下子元素的layout方法,子元素就会确定自身的位置以及相对于它的子元素onLayout方法。
我们来查看LinearLayout的onLayout方法:
@Override
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);
}
}
依然分为横向和竖向,查看竖向
void layoutVertical(int left, int top, int right, int bottom) {
final int paddingLeft = mPaddingLeft;
//.....省略
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();
int gravity = lp.gravity;
if (gravity < 0) {
gravity = minorGravity;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
//...省略
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);
}
}
}
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
可以看到此方法遍历子元素,并调用setChildFrame来确定子元素位置,通过childTop 逐渐增大实现子元素的位置一个个往下排列。我们看setChildFrame里面是不是又调用了layout方法,这样就实现了一层层传递完成整个View树的layout。
- 总结来说layout过程:
在layout中确定自身位置并调用onLayout方法遍历子元素确定子元素位置。onLayout方法如何实现取决于每个实现类,一般会在onLayout方法遍历子元素并调用layout确定子元素的本身位置和遍历子元素的子元素
说明View的实际尺寸的问题
我们在上文反复提到测量尺寸和最终尺寸(实际尺寸)两个概念,并且说了测量尺寸并不代表View的最终尺寸,View的最终尺寸在layout中确定。来分析是如何确定的。
实际尺寸以宽例通过View的getWidth方法可获得:
public final int getWidth() {
return mRight - mLeft;
}
那么我们就来看看mRight ,mLeft在layout过程当中有没有赋值。我们可以看到在layout当中调用了setFrame给本身确定位置时有这么一段代码。没错,就是给mRight ,mLeft赋值并且等于传入的left,right。这就能说明View的最终尺寸是在layout的时候确定的。
protected boolean setFrame(int left, int top, int right, int bottom) {
//..省略
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
//..省略
}
那么为何又说测量尺寸并不代表最终尺寸,我们来看看调用setFrame方法的时候参数是怎么传的呢?我们接着上述LinearLayout的layoutVertical方法分析
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
setChildFrame(child, childLeft + getLocationOffset(child), childTop,childWidth, childHeight);
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
可以看到传入到child的layout当中的四个位置,正是通过childWidth,childHeight 计算所得,大家仔细看上述代码,这里最终尺寸(getWidth)和测量尺寸getMeasuredWidth是不是相等的?没错是相等的,甚至于绝大多数情况下我们的测量尺寸都等于实际尺寸,只是赋值的时机实际尺寸是在layout当中赋值比测量尺寸晚。那为何又说测量尺寸和最终尺寸不一定一样呢?
但是也确实也有特殊情况导致两者不一致,比如我重写了layout方法:
@Override
public void layout(int l, int t, int r, int b) {
super.layout(l, t, r+10, b+1);
}
三 draw过程
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
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)
* 7. If necessary, draw the default focus highlight
*/
// Step 1, draw the background, if needed
int saveCount;
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
onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
drawAutofilledHighlight(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);
// Step 7, draw the default focus highlight
drawDefaultFocusHighlight(canvas);
if (isShowingLayoutBounds()) {
debugDrawFocus(canvas);
}
// we're done...
return;
}
//.....省略
}
可总结出View的绘制步骤:
- 绘制背景 drawBackground(canvas);
- 绘制自己 onDraw(canvas);
- 绘制children dispatchDraw(canvas);
- 绘制装饰 onDrawScrollBars在onDrawForeground中调用
其中dispatchDraw遍历所有子元素的draw方法实现绘制过程的传递
- 关于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默认情况下启用,可以根据我们的实际开发需求进行改变。
以上就是View的整个工作流程了,从系统如何一步步分配到View,再如何一步步完成测量到位置的确定最后绘制出来。
参考:<<Android开发艺术探索>>