提起View的绘制流程,相信大家立刻就能想到耳熟闻详的三个方法:onMeasure(测量)、onLayout(布局)、onDraw(绘制),这三个方法的确参与了View的绘制流程,除此之外还有MeasureSpec、LayoutParams等等。今天笔者就带领大家由顶级View:DecorView开始,从上至下,将View的绘制流程整体贯穿一下,希望大家阅读完本文后都能有所收获。
了解Activity窗口机制的朋友们肯定知道,DecorView作为Activity的顶级View,它本身是一个FrameLayout,DecorView下只有一个直接的子View,那就是LinearLayout,该LinearLayout的排列方式为竖直排列,包括有标题栏和id为content的内容部分,我们在Activity的onCreate方法中通过setContentView加载的布局文件就是作为直接子View add到这个id为content的FrameLayout中。好了,在这里我新创建一个Activity,对应的布局文件如下,下面我们就以此为例,由DecorView开始,从上至下来分析下View的绘制流程。
View绘制流程的起点为ViewRootImpl类中的performTraversals()方法,我们打开源码看下(为了便于分析,源码有所删减):
private void performTraversals() {
...
//1.获取DecorView的测量规则,其中mWidth为屏幕的宽度,mHeight为屏幕的高度
//lp为DecorView自身的布局参数LayoutParams
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
//2.完成整个ViewTree的测量工作
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
...
//3.完成整个ViewTree的布局工作
performLayout(lp, mWidth, mHeight);
...
//4.完成整个ViewTree的绘制工作
performDraw();
}
可以看到,在performTraversals方法中,首先调用到getRootMeasureSpec方法,创建顶级View DecorView的测量规则,接着依次调用到performMeasure、performLayout、performDraw方法,分别完成整个ViewTree的测量、布局、以及绘制工作。
我们首先看下1处DecorView MeasureSpec的创建,在这里我先简单说一下,DecorView测量规则的创建和我们普通View(包括有View以及ViewGroup)测量规则的创建略有不同。对于DecorView而言,它的MeasureSpec是由窗口尺寸和它自身的LayoutParams共同决定的,而我们的普通View,它的MeasureSpec则是由父容器的MeasureSpec和它自身的LayoutParams共同决定的。这一点通过源码就可以看出来。1处调用到getRootMeasureSpec方法,完成DecorView MeasureSpec的创建,getRootMeasureSpec方法中传的第一个参数为屏幕的宽高,第二个参数为DecorView自身的LayoutParams,不知道你有没有好奇DecorView的布局参数具体是什么呢?我们点进去 lp ,看下它是在哪里赋值的:
private void performTraversals() {
...
WindowManager.LayoutParams lp = mWindowAttributes;
}
你没看错,就是在performTraversals方法中一开始赋值的,那 mWindowAttributes 又是在哪里赋值的呢,我们接着跟:
final WindowManager.LayoutParams mWindowAttributes = new WindowManager.LayoutParams();
mWindowAttributes 为ViewRootImpl类中定义的final类型的成员变量,我们跟进去WindowManager.LayoutParams:
# WindowManager
public static class LayoutParams extends ViewGroup.LayoutParams implements Parcelable {
...
public LayoutParams() {
super(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
type = TYPE_APPLICATION;
format = PixelFormat.OPAQUE;
}
...
}
这下真相大白了吧,DecorView的布局参数lp.width为MATCH_PARENT,lp.height为MATCH_PARENT。好了好了,我们接着回到performTraversals()中的1处,跟进去getRootMeasureSpec方法,看下DecorView的MeasureSpec具体是怎么创建的:
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
int measureSpec;
switch (rootDimension) {
//1.
case ViewGroup.LayoutParams.MATCH_PARENT:
// Window can't resize. Force root view to be windowSize.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
//2.
case ViewGroup.LayoutParams.WRAP_CONTENT:
// Window can resize. Set max size for root view.
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
//3.
default:
// Window wants to be an exact size. Force root view to be that size.
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}
通过上述代码,DecorView MeasureSpec的创建过程就很明确了,由于DecorView的布局参数lp.width为MATCH_PARENT,lp.height为MATCH_PARENT,所以程序实际上只会走第一个case语句。即DecorView 宽度SpecMode为MeasureSpec.EXACTLY,SpecSize为屏幕宽度,高度SpecMode为MeasureSpec.EXACTLY,SpecSize为屏幕高度。
我们接着回到performTraversals方法中,接着就是2处的performMeasure方法,跟进去:
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
if (mView == null) {
return;
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
try {
//重点
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
performMeasure方法中传入的第一个参数childWidthMeasureSpec就是decorview宽度测量规则,传入的第二个参数childHeightMeasureSpec就是decorview高度测量规则,mView就是我们的decorview对象,可以看到performMeasure方法中调用到decorview的measure方法,将decorview的宽度测量规则和高度测量规则直接作为参数传入。我们跟进去decorview的measure方法看下(DecorView本质为FrameLayout,FrameLayout继承自ViewGroup,ViewGroup继承自View类,实质调用到View类的measure方法):
#View
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
...
onMeasure(widthMeasureSpec, heightMeasureSpec);
...
}
接着跟进去decorview的onMeasure方法:
#DecorView
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
...
//重点,调用到FrameLayout的onMeasure方法
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
...
}
我们来到FrameLayout类的onMeasure方法看下:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//获取到子View的数量,在这里由于我们的decorview只有一个直接的子View,那就是一个竖直排列的LinearLayout,所以count为1
int count = getChildCount();
//由我们上述分析可知,decorview的宽度测量规则为MeasureSpec.EXACTLY,高度测量规则为MeasureSpec.EXACTLY
//所以在这里measureMatchParentChildren的值 计算为false
final boolean measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
//mMatchParentChildren为ArrayList,调用mMatchParentChildren.clear()方法后,mMatchParentChildren的size为0
mMatchParentChildren.clear();
// maxHeight 代表framelayout中最大高度
// maxWidth 代表framelayout中最大宽度
int maxHeight = 0;
int maxWidth = 0;
int childState = 0;
//遍历framelayout中的所有子View,完成以该framelayout对象为首的ViewTree,其下所有子View的测量工作
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
if (mMeasureAllChildren || child.getVisibility() != GONE) {
//1. 重点!!!对子View进行测量
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
//由FrameLayout的布局特点决定,framelayout的宽度为所有子view的最大宽度(将子view的leftMargin 以及 rightMargin考虑在内)+ 该framelayout的leftpadding 和 rightpadding
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());
//在这里mMatchParentChildren 为false,所以 mMatchParentChildren的 size 一直为 0
if (measureMatchParentChildren) {
if (lp.width == LayoutParams.MATCH_PARENT ||
lp.height == LayoutParams.MATCH_PARENT) {
mMatchParentChildren.add(child);
}
}
}
}
//考虑到framelayout的padding
maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();
// 考虑到framelayout的最小宽度和高度
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());
}
//2. 设置framelayout的测量宽高,在这里为设置decorview的测量宽高
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(maxHeight, heightMeasureSpec,
childState << MEASURED_HEIGHT_STATE_SHIFT));
count = mMatchParentChildren.size();
//在这里count为 0 ,if 语句代码块不执行
if (count > 1) {
...
}
}
上述代码中重点部分已经做了详细的标注,相信大家都能理解,在这里FrameLayout就是我们的decorview对象,其下只有一个子View,那就是一个竖直排列的LinearLayout。所以measureChildWithMargins方法在这里完成了decorview中LinearLayout对象的测量。我们跟进去measureChildWithMargins方法看下:
#ViewGroup类
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);
}
可以看到,在 measureChildWithMargins 方法中,首先获取到子View的LayoutParams,然后调用getChildMeasureSpec方法来创建子View的MeasureSpec,最后调用到子View的measure方法,将子View的MeasureSpec作为参数传入。同时我们还可以分析出,子View MeasureSpec的创建与父容器的MeasureSpec和子View本身的LayoutParams有关,除此之外,还与父容器的padding以及子View的margin有关。我们跟进去 getChildMeasureSpec方法,看下子View的MeasureSpec具体是怎么创建的:
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
//获取到父容器的测量模式
int specMode = MeasureSpec.getMode(spec);
//获取到父容器的测量大小
int specSize = MeasureSpec.getSize(spec);
//padding指父容器中已占用空间大小,size为当前子View最大可用大小
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的MeasureSpec的创建规则,在这里就不赘述了。
好了,我们回到measureChildWithMargins方法中接着往下看,在这里decorview中子View LinearLayout对象的MeasureSpec创建完毕后,后续调用到LinearLayout的measure方法,将LinearLayout的测量规则传入,我们跟进去:
#View 同样是调用到View类
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
...
onMeasure(widthMeasureSpec, heightMeasureSpec);
...
}
由于LinearLayout重写了View类的onMeasure方法,所以我们跟进去LinearLayout的onMeasure方法看一下:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
由上述代码可以看到,在LinearLayout的onMeasure方法中首先对 mOrientation的值进行了判断,mOrientation代表当前LinearLayout的排列顺序,我们说过,decorview中的LinearLayout的排列方式为竖直排列,所以 mOrientation == VERTICAL 的值为 true,我们跟进去 measureVertical方法去看下:
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
// See how tall everyone is. Also remember max width.
for (int i = 0; i < count; ++i) {
...
//1.
measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
heightMeasureSpec, usedHeight);
...
}
//2.
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
...
}
在LinearLayout的 measureVertical 方法中,同样是首先遍历当前LinearLayout下的所有子View,调用 measureChildBeforeLayout 方法完成当前LinearLayout下所有子View的测量工作,最后调用到 setMeasuredDimension方法,设置自己的测量宽高。我们跟进去 measureChildBeforeLayout方法:
#LinearLayout
void measureChildBeforeLayout(View child, int childIndex,
int widthMeasureSpec, int totalWidth, int heightMeasureSpec,
int totalHeight) {
measureChildWithMargins(child, widthMeasureSpec, totalWidth,
heightMeasureSpec, totalHeight);
}
哈哈哈,LinearLayout的 measureChildBeforeLayout方法中同样是调用到ViewGroup类的 measureChildWithMargins方法,首先获取到子View的MeasureSpec,然后调用到子View的measure方法来完成子View的测量工作。由于当前LinearLayout对象为DecorView的直接子View,所以当前LinearLayout的子View就是titlebar标题栏和id为content的FrameLayout。后续的测量过程类似,在这里我就不再赘述了。。。
好了,我们回过头接着分析下decorview中LinearLayout测量完毕后的操作,那就是2处的setMeasuredDimension方法。setMeasuredDimension方法接收两个参数,第一个参数为measuredWidth,就是测量后的宽度,第二个参数为measuredHeight,就是测量后的高度。由上述代码可以看到,decorview宽高的测量值是由resolveSizeAndState方法决定的,我们跟进去看下:
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);
}
由于decorview的宽度SpecMode和高度SpecMode都为MeasureSpec.EXACTLY,宽度的SpecSize和高度SpecSize分别为 屏幕宽度 和
屏幕高度 ,所以针对decorview而言,在resolveSizeAndState方法中只会走 case MeasureSpec.EXACTLY:代码块,即将屏幕宽度和屏幕高度直接return掉,我们接着看下setMeasuredDimension方法:
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
boolean optical = isLayoutModeOptical(this);
if (optical != isLayoutModeOptical(mParent)) {
Insets insets = getOpticalInsets();
int opticalWidth = insets.left + insets.right;
int opticalHeight = insets.top + insets.bottom;
measuredWidth += optical ? opticalWidth : -opticalWidth;
measuredHeight += optical ? opticalHeight : -opticalHeight;
}
//重点
setMeasuredDimensionRaw(measuredWidth, measuredHeight);
}
接着跟进去setMeasuredDimensionRaw方法:
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
}
可以看到在setMeasuredDimensionRaw方法中直接将我们传进来的measuredWidth 和 measuredHeight分别赋值给 decorview的成员变量: mMeasuredWidth 和 mMeasuredHeight 。即decorview的测量宽度为屏幕宽度,测量高度为屏幕高度。
按照程序代码的执行流程,到此为止,整个ViewTree的测量工作就完毕了,接下来程序会回到 ViewRootImpl 类中的 performTraversals方法接着执行 3 处的performLayout方法,来完成整个ViewTree的布局工作。我们跟进去看下:
#ViewRootImpl
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
mLayoutRequested = false;
mScrollMayChange = true;
mInLayout = true;
//首先判断decorview对象是否为null,如果decorview为null,直接return掉
final View host = mView;
if (host == null) {
return;
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "layout");
try {
//重点!!!调用到decorview的layout方法
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
mInLayout = false;
...
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
mInLayout = false;
}
我们接着跟进去decorview的layout方法看下:
#ViewGroup类
//对View类的layout方法进行了重写,所以首先会调用到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);
}
//调用到View类中的layout方法
super.layout(l, t, r, b);
} else {
// record the fact that we noop'd it; request layout when transition finishes
mLayoutCalledWhileSuppressed = true;
}
}
我们接着跟进去View类的layout方法:
#View
public void layout(int l, int t, int r, int b) {
...
//1.调用setFrame方法,确定View本身的位置,在这里是确定decorview自身的位置
boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
//2.调用到onLayout方法,确定子View的位置,在这里是确定decorview下LinearLayout的位置
onLayout(changed, l, t, r, b);
...
}
}
我们首先跟进去1处的setFrame方法:
protected boolean setFrame(int left, int top, int right, int bottom) {
...
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
...
}
可以看到在setFrame方法中将我们传进来的left、top、right、bottom分别赋值给mLeft、mTop、mRight、mBottom。就这样,decorview的位置就确定了。我们回过头接着看 2处decorview的onLayout方法,跟进去看下:
#DecorView
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
//调用到FrameLayout类中的onLayout方法
super.onLayout(changed, left, top, right, bottom);
...
}
我们跟进去FrameLayout类中看下:
#FrameLayout
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
layoutChildren(left, top, right, bottom, false /* no force left gravity */);
}
接着跟进去layoutChildren方法:
#FrameLayout
void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
//获取到framelayout中子View的数量
final int count = getChildCount();
//分别获取到子View的left、right、top、bottom的边界坐标区域,
//坐标系转换,以当前父容器的左上角为坐标系原点,水平向右为X轴正向,竖直向下为Y轴正向。
//在这里 layoutChildren 方法传入的 left、top、right、bottom的值是当前父容器作为子View相对于其父容器来讲的坐标值,经过相减操作后就将坐标系转换成以当前父容器为基准坐标系
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();
//获取到当前子View的测量宽高值
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;
//确定当前子View的left坐标
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;
}
//确定当前子View的top坐标
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;
}
//重点!!!调用到子View的layout方法,将当前子View的left、top、right、bottom坐标值作为参数传入
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}
上述代码中的注释已经很清楚了,在这里,当前父容器指的就是我们的decorview,所以计算好decorview下 linearLayout的坐标值后会调用LinearLayout的layout方法,确定linearLayout的位置,我们跟进去LinearLayout的layout方法去看下(同样调用到View类的layout方法):
#View
public void layout(int l, int t, int r, int b) {
...
//1.调用setFrame方法,确定View本身的位置,在这里是确定decorview下LinearLayout自身的位置
boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
//2.调用到onLayout方法,确定子View的位置,在这里是确定LinearLayout下titlebar和id为content的FrameLayout的位置
onLayout(changed, l, t, r, b);
...
}
}
LinearLayout类对onLayout方法进行了重写,所以我们跟进去看下:
#LinearLayout
@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);
}
}
decorview下的LinearLayout的排列方式为竖直排列,mOrientation == VERTICAL 的值为true,所以我们来到 layoutVertical方法:
#LinearLayout
void layoutVertical(int left, int top, int right, int bottom) {
final int paddingLeft = mPaddingLeft;
int childTop;
int childLeft;
// 获取到子View的right边界坐标值
final int width = right - left;
int childRight = width - mPaddingRight;
// 子View水平方向可用空间
int childSpace = width - paddingLeft - mPaddingRight;
//获取到子view的数量
final int count = getVirtualChildCount();
final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
//根据当前linearlayout的gravity属性值确定第一个子View的top坐标值
switch (majorGravity) {
case Gravity.BOTTOM:
// mTotalLength contains the padding already
childTop = mPaddingTop + bottom - top - mTotalLength;
break;
// mTotalLength contains the padding already
case Gravity.CENTER_VERTICAL:
childTop = mPaddingTop + (bottom - top - mTotalLength) / 2;
break;
case Gravity.TOP:
default:
childTop = mPaddingTop;
break;
}
for (int i = 0; i < count; i++) {
final View child = getVirtualChildAt(i);
if (child == null) {
childTop += measureNullChild(i);
} else if (child.getVisibility() != GONE) {
//获取到LinearLayout下子View的测量宽高
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);
//根据子View的属性值layout_gravity,确定子View的left坐标值
switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.CENTER_HORIZONTAL:
childLeft = paddingLeft + ((childSpace - childWidth) / 2)
+ lp.leftMargin - lp.rightMargin;
break;
case Gravity.RIGHT:
childLeft = childRight - childWidth - lp.rightMargin;
break;
case Gravity.LEFT:
default:
childLeft = paddingLeft + lp.leftMargin;
break;
}
if (hasDividerBeforeChildAt(i)) {
childTop += mDividerHeight;
}
//考虑到子View的layout_marginTop值
childTop += lp.topMargin;
//1. 调用到setChildFrame方法,确定子View的坐标位置
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
//当前父容器linearlayout的排列方式为竖直排列,所以childTop的值需要自增加上当前子View的测量高度以及子View bottomMargin的值
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
我们接着跟进去1处的 setChildFrame方法:
#LinearLayout
private void setChildFrame(View child, int left, int top, int width, int height) {
child.layout(left, top, left + width, top + height);
}
可以看到在LinearLayout的 setChildFrame 方法中直接调用到子View的layout方法,将子View的left、top、right、bottom坐标值作为参数传了进去。由于我们当前的LinearLayout为DecorView下的LinearLayout,所以这里的子View为titleBar和id为content的FrameLayout。后续的layout流程类似,这里笔者就赘述了。。。
整个ViewTree的layout布局工作完成以后,程序会回到 ViewRootImpl 类中的performTraversals()方法接着向下执行,也就是调用到 4 处的 performDraw 方法,完成整个ViewTree的绘制工作,我们跟进去看下:
#ViewRootImpl
private void performDraw() {
...
try {
//重点
draw(fullRedrawNeeded);
} finally {
mIsDrawing = false;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
...
}
我们接着跟进去 ViewRootImpl 类的draw方法去看下:
private void draw(boolean fullRedrawNeeded) {
...
if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
return;
}
...
}
我们紧着跟进去 drawSoftware 方法:
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
boolean scalingRequired, Rect dirty) {
...
try {
//调整画布位置
canvas.translate(-xoff, -yoff);
if (mTranslator != null) {
mTranslator.translateCanvas(canvas);
}
canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
attachInfo.mSetIgnoreDirtyState = false;
//重点!!!调用到decorview的draw方法
mView.draw(canvas);
drawAccessibilityFocusedDrawableIfNeeded(canvas);
} finally {
if (!attachInfo.mSetIgnoreDirtyState) {
// Only clear the flag if it was not set during the mView.draw() call
attachInfo.mIgnoreDirtyState = false;
}
}
...
}
在 ViewRootImpl 类中的 drawSoftware 方法中终于调用到 decorview的draw方法进行绘制操作,我们跟进去看下:
#DecorView
@Override
public void draw(Canvas canvas) {
//调用到View类中的draw方法
super.draw(canvas);
if (mMenuBackground != null) {
mMenuBackground.draw(canvas);
}
}
可以看到在DecorView的draw方法中直接调用到 View类的draw方法,我们跟进去看下:
#View类
@CallSuper
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);
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 (debugDraw()) {
debugDrawFocus(canvas);
}
// we're done...
return;
}
...
}
从上述代码可以看出,View的绘制过程遵循如下几步:1. 调用 drawBackground 方法绘制自身的背景 2. 调用 onDraw 方法绘制自己 3. 调用 dispatchDraw 方法绘制children 4. 调用 onDrawForeground 方法绘制装饰。
在这里当前View为decorview,所以decorview首先调用到onDraw方法绘制自己,然后调用到 dispatchDraw 方法绘制children,也就是decorview下的linearlayout对象。我们首先看下decorview的onDraw方法:
#DecorView
@Override
public void onDraw(Canvas c) {
//重点,直接调用到View类的onDraw方法
super.onDraw(c);
// When we are resizing, we need the fallback background to cover the area where we have our
// system bar background views as the navigation bar will be hidden during resizing.
mBackgroundFallback.draw(isResizing() ? this : mContentRoot, mContentRoot, c,
mWindow.mContentParent);
}
我们跟进去View类的onDraw方法去看下:
/**
* Implement this to do your drawing.
*
* @param canvas the canvas on which the background will be drawn
*/
protected void onDraw(Canvas canvas) {
}
对的你没有看错,decorview的onDraw方法内部只是调用到 mBackgroundFallback.draw,具体什么操作我们就不追究了,我们回过头接着看下decorview的dispatchDraw方法:
#ViewGroup
@Override
protected void dispatchDraw(Canvas canvas) {
...
more |= drawChild(canvas, child, drawingTime);
...
}
接着看下 drawChild 方法:
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
//重点
return child.draw(canvas, this, drawingTime);
}
可以看到在 drawChild 方法中直接调用到 child.draw方法,由于我们当前View为decorview,也就是调用到decorview下linearlayout的draw方法,后续绘制流程类似,这里就不再赘述了。。。
整个ViewTree的绘制工作执行完毕后,确切说,ViewRootImpl 类中的performTraversals()方法就执行完毕了。
到这里为止,我们就从顶级View DecorView从上至下,将整个ViewTree的绘制流程贯穿了一遍。文章略长,感谢大家有耐心读完本文。