在 Android 的知识体系中,View 扮演着很重要的角色。只有对 View 的相关机制深入理解之后,才能通过自定义 View 实现各种效果,以及处理开发中遇到的各种问题。
我们知道 View 的绘制过程有三大重要的过程,即 View 的 measure 、layout 和 draw 过程。在 Android 中 Activity Window ViewRootImpl 的关联 这篇文章中,我们知道 ViewRootImpl 类是绑定 View 和 Window 中重要的一环, 而View 的绘制过程就是从从 ViewRootImpl 中开始的:
root = new ViewRootImpl(view.getContext(), display);
root.setView(view, wparams, panelParentView);
ViewRootImpl 的 setView 方法最终会调用到 performTraversals 方法开始 View 的绘制工作。绘制的大致流程可用下图来表示。
View 绘制过程performTraversals 方法会依次调用 performMeasure、performLayout 和 performDraw 方法。三个方法分别调用顶级 View 的 measure、layout 和 draw 方法。而在 ViewGroup 的 performMeasure 方法中会调用到 measure 方法,measure 方法调用 onMeasure 方法。在 onMeasure 方法中遍历子类的 measure 方法。
同理 layout 和 draw 方法与此类似。
我们知道 ,顶层 View 即为 DecorView ,而 DecorView 继承于 FrameLayout,所以绘制过程从 FrameLayout 开始。
在了解绘制 Measure 任务开始之前,首先介绍一下和测量紧密相关的类 MeasureSpec:
public static class MeasureSpec {
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
public static final int EXACTLY = 1 << MODE_SHIFT;
public static final int AT_MOST = 2 << MODE_SHIFT;
public static int makeMeasureSpec(int size, int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
public static int getMode(int measureSpec) {
return (measureSpec & MODE_MASK);
}
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
......
}
MeasureSpec 封装了一个 32 位的 int 值,其中高 2 位表示 SpecMode ,低 30 位表示 SpecSize。SpecMode 指的是测量模式,SpecSize 表示测量规格的大小。 SpecMode 和 SpecSize 打包在一起构成 MeasureSpec。
SpecMode 有三类:
UNSPECIFIED
对 view没有任何限制,要多大给多大。一般用于系统内部。
EXACTLY
给出了测出 View 所需要的精确大小,这个时候子 View 的最终大小就是 SpecSize 对应的值。一般对应 LayoutParams 中的 match_parent 和具体的数值大小。
AT_MOST
指定了一个可用大小 SpecSize, View 的大小不能大于这个值,具体值需要查看对应子 View 具体的实现。对应 LayoutParams 中的 warp_content。
上面说到 MeasureSpec 和 View 的测量相关,正常情况下使用 View 都会使用 MeasureSpec,同时我们也可以给 View 设置 LayoutParams。而 View 最终的宽高测量 MeasureSpec 由自己 LayoutParams 和 父容器的 MeasureSpec 一起确定的。
接下来去查看具体的测量过程,既然绘制过程 ViewRootImpl 开始,查看 ViewRootImpl 的 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);
}
}
performMeasure 会调用到 View 的 measure 方法,我们知道 mView 是 DecorView,而 DecorView 继承自 FragmentLayout。而 FragmentLayout 的 measure 方法的最终实现类在 View 中:
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
......
final boolean forceLayout = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT;
final boolean isExactly = MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY;
final boolean matchingSize = isExactly &&
getMeasuredWidth() == MeasureSpec.getSize(widthMeasureSpec) &&
getMeasuredHeight() == MeasureSpec.getSize(heightMeasureSpec);
if (forceLayout || !matchingSize &&
(widthMeasureSpec != mOldWidthMeasureSpec ||
heightMeasureSpec != mOldHeightMeasureSpec)) {
// first clears the measured dimension flag
mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;
resolveRtlPropertiesIfNeeded();
int cacheIndex = forceLayout ? -1 : mMeasureCache.indexOfKey(key);
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// measure ourselves, this should set the measured dimension flag back
onMeasure(widthMeasureSpec, heightMeasureSpec);
mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
} else {
long value = mMeasureCache.valueAt(cacheIndex);
// Casting a long to int drops the high 32 bits, no mask needed
setMeasuredDimensionRaw((int) (value >> 32), (int) value);
mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
}
// flag not set, setMeasuredDimension() was not invoked, we raise
// an exception to warn the developer
if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {
throw new IllegalStateException("onMeasure() did not set the"
+ " measured dimension by calling"
+ " setMeasuredDimension()");
}
mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
}
mOldWidthMeasureSpec = widthMeasureSpec;
mOldHeightMeasureSpec = heightMeasureSpec;
mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |
(long) mMeasuredHeight & 0xffffffffL); // suppress sign extension
}
这里会判断有没有设置 PFLAG_FORCE_LAYOUT ,如果没有设置并且 mMeasureCache 有缓存,会继续调用 onMeasure 方法,这里就会回到上层 FragmentLayout 中的 onMeasure 方法:
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));
}
onMeasure 方法会遍历子类,并调用 measureChildWithMargin 方法,而且 FragmentLayout 的测量会依赖于子类的测量宽高进行叠加并最终调用 setMeasuredDimension 方法完成自己的测量,先进行查看 measureChildWithMargin 方法:
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);
}
在对子元素进行 measure 测量之前,会通过 getChildMeasureSpec 方法 获取到子元素的 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 = 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);
}
上述方法,主要就是根据父容器的 MeasureSpec 同时结合子 View 本身的 LayoutParams 来确定子元素的 MeasureSpec 。
针对上面的确定规则,可以用一张表进行梳理:
MeasureSpec的测量针对 View 的 MeasureSpec 的测量,前面提到,普通 View 的 MeasureSpec 是由父容器的 MeasureSpec 和 自身的 LayoutParams 共同确定的。那么针对不同的父容器 和 View 本身不同的 LayoutParams,View 可以有多种 MeasureSpec:
1 View 的设置固定宽高的时候 ,不管父容器 MeasureSpec 是什么,View 本身 MeasureSpec 都遵从精准模式,且大小是设置的大小。
2 当 View 的宽高设置是 match_parent 的时候,如果父容器是精准模式,那么 View 也是精准模式并且大小和父容器剩余空间一样大,如果父容器是最大模式,那么 View 也是最大模式并且大小不超过父容器的最大空间。
3 当 View 设置宽高为 warp_content 的时候,不管父容器是精准模式还是最大化模式,View总是最大化模式,且大小不能超过父容器的剩余空间。
获取了View 的 MeasureSpec 数据之后,继续去调用子类 View 的 measure 方法:
继续调用子类 View 的 measure 方法,和上述 measure 方法调用一样,此时一定会再次调用到 onMeasure方法,上面因为 FragmentLayout 重写了 onMeasure 方法,所以调用到 FragmentLayout 的 onMeasure 方法,如果此时的 View 没有重写 onMeasure,则进入到 View 自己的 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 针对 AT_MOST 和 EXACTLY 两个模式,获取到的 size 其实就是我们测量出来的大小。UNSPECIFIED 一般用内部测量。
getSuggestedMinimumWidth 方法会根据 View 是否设置背景以及设置的相关 minWidth 和 maxWidth 属性来获取最小值,如果没有进行设置就是测量值的大小。
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
到这里 View 的 measure 测量流程走完。会遍历完成所有子类的方法完成测量,并最终叠加计算完成 FragmentLayout 自己的测量,在上述流程已经提到过。
同理,接下来类似继续以 DecorView 往下调用查看 performLayout 的方法:
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
......
final View host = mView;
if (DEBUG_ORIENTATION || DEBUG_LAYOUT) {
Log.v(TAG, "Laying out " + host + " to (" +
host.getMeasuredWidth() + ", " + host.getMeasuredHeight() + ")");
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
try {
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
if (validLayoutRequesters != null) {
final ArrayList<View> finalRequesters = validLayoutRequesters;
// Post second-pass requests to the next frame
getRunQueue().post(new Runnable() {
@Override
public void run() {
int numValidRequests = finalRequesters.size();
for (int i = 0; i < numValidRequests; ++i) {
final View view = finalRequesters.get(i);
Log.w("View", "requestLayout() improperly called by " + view +
" during second layout pass: posting in next frame");
view.requestLayout();
}
}
});
}
}
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
mInLayout = false;
}
和 measure 方法类似,可以直接去看 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 前后 layout 有没有变化,如果有变化调用到 DecorView 的 父类 FragmentLayout 中的 onLayout 方法:
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();
mForegroundBoundsChanged = true;
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);
}
}
}
看过 measure 测量之后这里就更好理解了,同样遍历子类,然后再去调用子类的 layout 方法,直至整 过程完成。这里的 layout 进行布局是 FragmentLayout 的方式,像 LinerLayout 和 RealativeLayout 的 onLayout 的实现方式又会不一样。具体可以自行研究。如果是自定义 View 则需根据需求来进行编写。
继续调用 draw 方法进行绘制。
有了上面的流程解析,这里就可以直接定位去看 View 中的 draw 方法:
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);
// Step 6, draw decorations (scrollbars)
onDrawScrollBars(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// we're done...
return;
}
上面注释已经给了详细的解释 draw 方法的相关主要步骤:
1 绘制背景 drawBackground(canvas)。
2 绘制内容 onDraw(canvas) 。
3 绘制子类 dispatchDraw(canvas)。
4 绘制装饰 onDrawScrollBars(canvas)。
dispatchDraw 方法实现 View 的传递,遍历所有的子类进行绘制。
通过以上分析,已经完成了一个 View 的绘制过程,在实际开发中会有各式各样的需求,其本质就是根据具体的需求实现 onMeasure、onLayout、onDraw 方法从而达到不同的效果。
网友评论