了解View的绘制对自定义控件的开发有着重要的意义,上一篇已经对activity加载UI的流程进行了讲解,从中可以看出DecorView是我们的最外层View,是一个FrameLayout的子类,View的绘制也是从DecorView开始的。
DecorView调用performTraversals()方法开始View的绘制,这个方法内容比较多,比较核心的是调用如下方法:
- performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
- performLayout(lp, desiredWindowWidth, desiredWindowHeight);
- performDraw();
这3个方法分别代表着View绘制的三个过程:measure(测量)、layout(摆放)、draw(绘制)。
如果我们自定义ViewGroup,那么我们需要重点关注measure、layout过程,ViewGroup的draw过程一般不需要去特殊处理。如果我们自定义View,draw的过程往往是最重要的,前面的一系列文章(坐标、Color、Path、Paint、Canvas等)讲解的知识主要就是为这个绘制过程准备的。
所以本篇文章着重介绍measure和layout两个过程,特别是measure过程,不仅重要性高还相对难理解。
measure过程
调用performMeasure开始进行测量
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
上面的方法调用了View的measure方法,这个方法传入两个int值,这个值就是测量规格MeasureSpec。它是一个32位的int值,分为两部分,前2位为mode,后30为size。mode的形式有3种:
- UPSPECIFIED : 没有明确限制,子View可根据自己的大小申请空间
- EXACTLY: 精确的大小,子View的必须跟设定的大小一致
- AT_MOST:最大值,子View的大小最大不超过给定的值
明白了这个参数的含义,那么childVIew的MeasureSpec是如何确定的呢?这个分为两种情况,一种是DecorView中确定子View的MeasureSpec调用ViewRootImplt的getRootMeasureSpec方法。
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;
}
从源码上可以分析出:
- 如果子View的宽高为MATCH_PARENT,那么它的MeasureSpec的mode为EXACTLY,大小为windowSize。原因是如果跟父布局一样大的话,父布局也就是DecorView的大小是确定的,所以mode为EXACTLY,大小为父布局给定的大小。
- 如果子View的宽高为WRAP_CONTENT,那么它的MeasureSpec的mode为AT_MOST,其最大值不超过windowSize。子View在DecorView内,最大值不超过DecorView的给定大小。
- 如果子View的宽高为确定值,也就是确定的值,那么它的MeasureSpec的mode为EXACTLY,值为子View宽高的值。因为给定了View的宽高,那么其mode即为EXACTLY。
另外一种为ViewGroup中确定子View的MeasureSpec调用ViewGroup的getChildMeasureSpec方法。
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 us
case 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 us
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
// Child wants a specific size... so be it
resultSize = 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 be
case MeasureSpec.UNSPECIFIED:
if (childDimension >= 0) {
// Child wants a specific size... let him have it
resultSize = childDimension;
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {
// Child wants to be our size... find out how big it should
// be
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
} else if (childDimension == LayoutParams.WRAP_CONTENT) {
// Child wants to determine its own size.... find out how
// big it should be
resultSize = 0;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
这个方法要比getRootMeasureSpec稍微复杂点,主要是因为DecorView的大小是确定的,DecorView继承自Framelayout,其确定MeasureSpec核心思想是一致的,如果getRootMeasureSpec只是getChildMeasureSpec方法的一个特例。
通过源码分可以分析出:
- 当ViewGroup的MeasureSpec为EXACTLY时,子View的MeasureSpec计算跟getRootMeasureSpec一致。
- 当ViewGroup的MeasureSpec为AT_MOST时:
- 如果子View为有确切的宽高,那么其MeasureSpec的mode为EXACTLY,值为其本身宽高的值。因为一点给定宽高,那么其mode为EXACTLY。
- 如果子View为MATCH_PARENT,那么其MeasureSpec的mode为AT_MOST,最大值为父布局的限定值。原因是父布局不知道大小,跟父布局一样宽高,所以不超过父布自身的最大值减去其它限制(padding等)也就是不超过父布局给子view的限定值。
- 如果子View为WRAP_CONTENT,那么其MeasureSpec的mode为AT_MOST,最大值为父布局的测限定的值。原因是父布局不知道大小,自己包裹内容,父布局不能超过自身的最大值,自己不能超过父布局限定的最大值。
- 当ViewGroup的MeasureSpec为UNSPECIFIED时:
- 如果子View为有确切的宽高,那么其MeasureSpec的mode为EXACTLY,值为其本身宽高的值。因为一点给定宽高,那么其mode为EXACTLY。
- 如果子View为MATCH_PARENT或者WRAP_CONTENT时,其MeasureSpec的mode为UNSPECIFIED,值为0.因为父布局不限定大小,所以子view也不限制,值的大小没有意义。
注意:因为父布局中存在Padding等属性,所以子View宽高在没有给定值的情况下,极限大小为父布局的大小减去额外开销。
View方法的measure方法代码量比较大,仔细分析可以发现测量过程主要通过onMeasure方法实现。这个方法是不可重写,因此View和ViewGroup在此方法的实现上是一致的。
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
……
onMeasure(widthMeasureSpec, heightMeasureSpec);
……
}
View和ViewGroup中的onMeasure方法有所不同,且不同的View如TextView、ImageView等onMeasure方法存在差异,不同的ViewGroup如LinearLayout、RelaiveLayout等的onMeasure方法也存在差异,下面就分情况举例说明。
View默认的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;
}
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
protected int getSuggestedMinimumHeight() {
return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());
}
getSuggestedMinimumWidth、getSuggestedMinimumHeight计算的是建议最小宽高,代码比较简单,需要综合背景和mMinWidth 来判断。
getDefaultSize则根据建议最小宽高和MeasureSpec的mode来确定,如果为UNSPECIFIED则返回最小建议宽高,如果是其它情况就返回MeasureSpec的值。
ViewGroup因为没有实现onMeasure方法,所以用Framelayout进行分析
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
mMatchParentChildren.clear();
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
maxWidth = Math.max(maxWidth,
child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
maxHeight = Math.max(maxHeight,
child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
childState = combineMeasuredStates(childState, child.getMeasuredState());
if (measureMatchParentChildren) {
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);
}
}
}
}
// Account for padding too
maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
// Check against our minimum height and width
maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());
// Check against our foreground's minimum height and width
final Drawable drawable = getForeground();
if (drawable != null) {
maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
}
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
count = mMatchParentChildren.size();
if (count > 1) {
for (int i = 0; i < count; i++) {
final View child = mMatchParentChildren.get(i);
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
final int childWidthMeasureSpec;
if (lp.width == LayoutParams.MATCH_PARENT) {
final int width = Math.max(0, getMeasuredWidth()
- getPaddingLeftWithForeground() - getPaddingRightWithForeground()
- lp.leftMargin - lp.rightMargin);
childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
width, MeasureSpec.EXACTLY);
} else {
childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
lp.leftMargin + lp.rightMargin,
lp.width);
}
final int childHeightMeasureSpec;
if (lp.height == LayoutParams.MATCH_PARENT) {
final int height = Math.max(0, getMeasuredHeight()
- getPaddingTopWithForeground() - getPaddingBottomWithForeground()
- lp.topMargin - lp.bottomMargin);
childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
height, MeasureSpec.EXACTLY);
} else {
childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
lp.topMargin + lp.bottomMargin,
lp.height);
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
}
}
这个方法相对较长,其核心无非是为每一个child计算MeasureSpec,然后计算出的宽高,接着根据自身的参数设置确定自己的宽高,最后调用setMeasuredDimension设置自己的大小。
计算出每个child在ViewGroup中基本都会出现,差别较大的是通过child计算自己的宽高。如LinearLayout和RelaiveLayout两种布局,LinearLayout在没有其它布局参数影响下,基本是child累加,而RelaiveLayout和Framelayout一样为child中的最大一个的值。
需要注意的是View和ViewGroup都需要在onMeasure过程中调用setMeasuredDimension设置自己的宽高,这也是这个方法存在的最终目的。
layout过程
layout过程跟Measure有一定的类似,在performMeasure调用了layout方法进行摆放。layout方法内调用onLayout方法进行子View的摆放。
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;
}
从源码中可以看到,layout的主要任务是通过调用setFrame来确定自己的位置和利用onLayout来摆放自己的child。
View类的onLayout方法如下:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
这个方法为空,因为View不存在子View,所以不存在摆放子View的过程。
ViewGroup类的layout方法如下:
@Override
public final void layout(int l, int t, int r, int b) {
if (!mSuppressLayout && (mTransition == null || !mTransition.isChangingLayout())) {
if (mTransition != null) {
mTransition.layoutChange(this);
}
super.layout(l, t, r, b);
} else {
// record the fact that we noop'd it; request layout when transition finishes
mLayoutCalledWhileSuppressed = true;
}
}
其实,除了一些额外的判断处理外,还是调用了父类也就是View的layout方法,主要流程跟上面分析的一致。
ViewGroup类的onLayout方法用abstract 修饰,需要子类去实现。
@Override
protected abstract void onLayout(boolean changed,
int l, int t, int r, int b);
Framelayout的onLayout的方法如下:
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
layoutChildren(left, top, right, bottom, false /* no force left gravity */);
}
void layoutChildren(int left, int top, int right, int bottom,
boolean forceLeftGravity) {
final int count = getChildCount();
final int parentLeft = getPaddingLeftWithForeground();
final int parentRight = right - left - getPaddingRightWithForeground();
final int parentTop = getPaddingTopWithForeground();
final int parentBottom = bottom - top - getPaddingBottomWithForeground();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
final int width = child.getMeasuredWidth();
final int height = child.getMeasuredHeight();
int childLeft;
int childTop;
int gravity = lp.gravity;
if (gravity == -1) {
gravity = DEFAULT_CHILD_GRAVITY;
}
final int layoutDirection = getLayoutDirection();
final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
if (!forceLeftGravity) {
childLeft = parentRight - width - lp.rightMargin;
break;
}
case Gravity.LEFT:
default:
childLeft = parentLeft + lp.leftMargin;
}
switch (verticalGravity) {
case Gravity.TOP:
childTop = parentTop + lp.topMargin;
break;
case Gravity.CENTER_VERTICAL:
childTop = parentTop + (parentBottom - parentTop - height) / 2 +
lp.topMargin - lp.bottomMargin;
break;
case Gravity.BOTTOM:
childTop = parentBottom - height - lp.bottomMargin;
break;
default:
childTop = parentTop + lp.topMargin;
}
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}
其实通过方法名字和可以看出,onLayout方法里调用layoutChildren对child进行摆放。通过布局参数计算出child的位置,调用child的layout方法进行摆放,如果child为View则回到View的layout方法,利用setFrame确定自己位置。如果child为ViewGroup则回到View的layout方法,除确定自己外置外,还需调用onLayout方法进行递归,摆放自己的子控件。
View的Measure和Layout过程到这里就分析完了,那么我们能利用它干点啥呢?好吧,那就先来解决一个简单而常见的问题——ListView或GridView嵌套。
嵌套的ListView或GridView无法展开,是因为其测量过程出现问题,我们只需要覆写下onMeasure方法,将其MeasureSpec的mode改为AT_MOST,大小设置为MeasureSpec值(30位)的最大值就行。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int heightSpec = View.MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, View.MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, heightSpec);
}
Layout过程有哪些应用呢,Layout的应用往往和measure过程配合使用,限于篇幅本篇不做介绍,后期会出一篇关于VIew绘制的实战,里面有相应的应用。