View绘制流程二:测量布局绘制
Posted <天各一方>
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了View绘制流程二:测量布局绘制相关的知识,希望对你有一定的参考价值。
文章目录
上篇博客我们详细分析了布局是如何添加到我们的界面上的,谈到ViewRootImpl的三个方法也就停止了,今天我们详细的分析measure、layout、draw三个过程。
Measure
理解MeasureSpec
什么是MeasureSpec
当我们要对我们的View进行测量时,要有一定的规则,我们不仅要考虑开发者在xml中给我们指定的layout,而且还要结合父View给我们指定的测量规则,这两个属性共同决定了我们子View的MeasureSpec,也就是子View的测量规则,按照这个MeasureSpec,我们就可以很轻松的解决测量时可能会遇到的问题。
MeasureSpec是一个32位的int值,高2位是SpecMode,它指的是测量模式,低30位是、SpecSize,它指的是在某种测量模式下的规格大小。MeasureSpec是将这两个打包成一个int值来避免过多对象内存分配,在MeasureSpec类内部提供了对这两个属性的操作。
MeasureSpec分类
-
UNSPECIFIED
父View不会对View有任何的限制,要多大给多大,这种情况一般用于系统内部。
-
EXACTLY
父View已经测出View所需的精确的大小,这个时候View的最终大小就是SpecSize所指定的值。它对应LayoutParams中的match_parent和具体数值这两种模式。
-
AT_MOST
父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值,具体是什么要看不同View的具体实现。它对应wrap_content属性。
MeasureSpec的创建
通过getChildMeasure就可以创建出子View的MeasureSpec:
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 = 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 be
resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
resultMode = MeasureSpec.UNSPECIFIED;
}
break;
}
//noinspection ResourceType
return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}
上述代码一图以蔽之:
View的measure
有了MeasureSpec,我们也可以放心的去测量我们的View了。View的measure过程是由其measure方法来完成,measure方法是一个final方法,子类不可以重写此方法,在View的measure方法中会调用View的onMeasure方法,因此我们直接看onMeasure方法:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
这个方法里,只用了一个方法就完成了View的measure过程,而通过方法名我们也知道这个方法时设置测量尺寸,那么参数就是测量过的尺寸了,所以我们看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;
}
这个方法也是很简单,UNSPECIFIED这个分支我们不去管他,而AT_MOST和EXACTLY这两个返回的结果是一样的,都是specSize,我们通过上面的表格也可以看出specSize是parentSize,是父View提供的可用空间。这就给我们自定义View提供了一个思路:继承View需要重写onMeasure并对wrap_content属性设置默认宽高,否则效果同match_parent一样,从源码我们也可以看出原因来。
ViewGroup的measure
对于ViewGroup来说,除了完成自己的measure过程以外,还要遍历的去调用所有子元素的measure方法,各个子元素再递归去执行这个过程。和View不同的是,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的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);
}
这个方法里,获取了子View的MeasureSpec,然后对子View进行测量。在继承ViewGroup实现自定义ViewGroup时,测量完子View的宽高后,就可以确定ViewGroup自身的宽高了。
Layout
Layout的作用是ViewGroup用来确定子元素的位置的,当ViewGroup的位置被确定后,它会在onLayout方法中遍历所有的子元素并调用其layout方法,在layout方法中,onLayout方法又会被调用。layout方法是确定其本身的位置,而onLayout方法是去确定所有子元素的位置。
简单看一看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);
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;
if (!wasLayoutValid && isFocused()) {
mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
if (canTakeFocus()) {
// We have a robust focus, so parents should no longer be wanting focus.
clearParentsWantFocus();
} else if (getViewRootImpl() == null || !getViewRootImpl().isInLayout()) {
// This is a weird case. Most-likely the user, rather than ViewRootImpl, called
// layout. In this case, there's no guarantee that parent layouts will be evaluated
// and thus the safest action is to clear focus here.
clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
clearParentsWantFocus();
} else if (!hasParentWantsFocus()) {
// original requestFocus was likely on this view directly, so just clear focus
clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
}
// otherwise, we let parents handle re-assigning focus during their layout passes.
} else if ((mPrivateFlags & PFLAG_WANTS_FOCUS) != 0) {
mPrivateFlags &= ~PFLAG_WANTS_FOCUS;
View focused = findFocus();
if (focused != null) {
// Try to restore focus as close as possible to our starting focus.
if (!restoreDefaultFocus() && !hasParentWantsFocus()) {
// Give up and clear focus once we've reached the top-most parent which wants
// focus.
focused.clearFocusInternal(null, /* propagate */ true, /* refocus */ false);
}
}
}
if ((mPrivateFlags3 & PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT) != 0) {
mPrivateFlags3 &= ~PFLAG3_NOTIFY_AUTOFILL_ENTER_ON_LAYOUT;
notifyEnterOrExitForAutoFillIfNeeded(true);
}
notifyAppearedOrDisappearedForContentCaptureIfNeeded(true);
}
通过setFrame来设置View四个顶点的位置,即初始化mLeft、mRight、mTop、mBottom。四个顶点的位置确定了,View在父容器的位置也就确定了。
Draw
Draw的过程就简单了,它的作用就是将View绘制到屏幕上面。View的绘制遵循着如下几步:
- 绘制背景
background.draw(canvas)
- 绘制自己
onDraw
- 绘制children
dispatchDraw
- 绘制装饰
onDrawScrollBars
这四个步骤在源码中也明显可以看出。View的onDraw是空实现,不同的控件对内容的绘制都不同,所以留给控件自己实现,我们自定义View时需要重写onDraw方法来绘制我们自己的控件。在ViewGroup中,也有对dispatchDraw的实现,dispatchDraw中对子View进行遍历,并调用了drawChild方法,其中又调用了View的draw方法,完成对子View的绘制。
自定义View时注意以下问题
- 让View支持wrap_content。
- 如果有必要,支持padding。
- 尽量不要在View中使用Handler。
- View中如果有线程或者动画,及时停止。
- View带有滑动嵌套情景时,处理好滑动冲突。
以上是关于View绘制流程二:测量布局绘制的主要内容,如果未能解决你的问题,请参考以下文章