前面的文章中我们介绍了DecorView,ViewRoot,并且我们介绍了DecorView如何添加到Window中。那么接着,我们就继续来看看,DecorView添加后,是如何进行后续的View绘制过程呢?本文源码均来自API 24。
首先我们又要来回顾一下ViewRoot这个类,这个类是一个非常非常重要的类。它是Window和View的纽带。这个类在之前的介绍中已经分析了其中一个功能:负责接收触摸,键盘事件等,并将它们进行传递到我们的Activity,子View等。现在我们来详细介绍另一个功能:负责触发View的绘制流程(即measure,layout,draw三大过程)。
简单介绍完了ViewRoot,接下来我们来开始跟着源码分析:
首先在之前的window.addView()将decorView添加到Window的过程中创建了ViewRoot,然后调用了viewRoot.setView()将window加入到windowManager。那么之前在setView()中我们只分析了添加的相关代码,现在我们回过头来看看其中的绘制代码:
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
if (mView == null) {
//将顶层视图DecorView赋值给全局的mView
mView = view;
..//其他代码
//标记已添加DecorView
mAdded = true;
.............
//请求布局
requestLayout();
..//其他代码
}
}
在上面的文章中我们可以看到调用了我们熟悉的requestLayout()方法。我们跟进去看看:
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
scheduleTraversals();
}
}
上面调用了几个方法,首先是checkThread()方法,我们跟进去看看:
void checkThread() {
if (mThread != Thread.currentThread()) {
throw new CalledFromWrongThreadException(
"Only the original thread that created a view hierarchy can touch its views.");
}
}
我们可以看到在这里进行了线程检查,这里也就是所谓的我们经常说的只有主线程才能操作UI的问题。但是其实看看这里的判断条件。并没有明确判断说当前线程是主线程。而且通过mThread是否是当前线程来判断。那么我们去看看这个mThread是什么?
上图中可以看出,是在新建ViewRoot的时候将当前线程赋给mThread。而我们的ViewRoot一般都是内部在主线程创建的。所以!!!!!所谓的子线程操作UI并不准确!理想情况下要是我们在子线程中创建ViewRoot,那么我们在主线程操作UI岂不是会报错?
上面的可以说是正餐点心,我们不深究,继续往下探索绘制流程。
在检查线程后,执行了 scheduleTraversals()方法,我们就继续看看:
void scheduleTraversals() {
if (!mTraversalScheduled) {
mTraversalScheduled = true;
mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
if (!mUnbufferedInputDispatch) {
scheduleConsumeBatchedInput();
}
notifyRendererOfFramePending();
pokeDrawLockIfNeeded();
}
}
我们看到在上面调用了mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);方法,在这里其实就是通过handler的方式将mTraversalRunnable进行异步执行,感兴趣的同学可以去看看。我们看看mTraversalRunnable里面的执行体代码:
final class TraversalRunnable implements Runnable {
@Override
public void run() {
doTraversal();
}
}
可以看到,只有一个doTraversal()方法:
void doTraversal() {
if (mTraversalScheduled) {
mTraversalScheduled = false;
mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
if (mProfile) {
Debug.startMethodTracing("ViewAncestor");
}
performTraversals();
if (mProfile) {
Debug.stopMethodTracing();
mProfile = false;
}
}
}
我们看到又调用了performTraversals()方法,终于看到我们熟悉的方法了,基本上所有网上的各种资料开头都是android的绘制过程从ViewRoot的performTraversals()开始。那么我们现在也终于知道了这个开始之前是怎么回事。接下来我们就继续一探究竟,继续跟入performTraversals()方法(贴出关键代码,这个方法代码估计有1千多行):
private void performTraversals() {
// cache mView since it is used so much below...
final View host = mView; //mView就是DecorView根布局
//是否正在遍历
mIsInTraversal = true;
//是否马上绘制View
mWillDrawSoon = true;
..//其他代码
//希望的窗口的宽高
int desiredWindowWidth;
int desiredWindowHeight;
//Window的参数
WindowManager.LayoutParams lp = mWindowAttributes;
if (mFirst) {
mFullRedrawNeeded = true;
mLayoutRequested = true;
//如果窗口的类型是有状态栏的,那么顶层视图DecorView所需要窗口的宽度和高度就是除了状态栏
if (lp.type == WindowManager.LayoutParams.TYPE_STATUS_BAR_PANEL
|| lp.type == WindowManager.LayoutParams.TYPE_INPUT_METHOD) {
// NOTE -- system code, won't try to do compat mode.
Point size = new Point();
mDisplay.getRealSize(size);
desiredWindowWidth = size.x;
desiredWindowHeight = size.y;
} else {//否则顶层视图DecorView所需要窗口的宽度和高度就是整个屏幕的宽高
DisplayMetrics packageMetrics =
mView.getContext().getResources().getDisplayMetrics();
desiredWindowWidth = packageMetrics.widthPixels;
desiredWindowHeight = packageMetrics.heightPixels;
}
}
..//其他代码
//在构造方法中mFirst已经设置为true,表示是否是第一次绘制DecorView
..//其他代码
//获得view宽高的测量规格,mWidth和mHeight表示窗口的宽高,lp.widthhe和lp.height表示DecorView根布局宽和高
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
// Ask host how big it wants to be
//执行测量操作
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
..//其他代码
//执行布局操作
performLayout(lp, desiredWindowWidth, desiredWindowHeight);
..//其他代码
//执行绘制操作
performDraw();
}
从上面代码可以看到整个路程还是很清晰的,从上到下先后调用了performMeasure(), performLayout(),performDraw()方法来完成整个绘制流程。我们先来看看performMeasure()方法,首先方法有两个参数,我们来看看代码怎么设置的。都执行了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;
}
我们先来简单地介绍下MeasureSpec的概念。
MeasureSpec是一个32位整数,由SpecMode和SpecSize两部分组成,其中,高2位为SpecMode,低30位为SpecSize。SpecMode为测量模式,SpecSize为相应测量模式下的测量尺寸。View(包括普通View和ViewGroup)的SpecMode由本View的LayoutParams结合父View的MeasureSpec生成。
SpecMode的取值可为以下三种:
EXACTLY: 对子View提出了一个确切的建议尺寸(SpecSize);
AT_MOST: 子View的大小不得超过SpecSize;
UNSPECIFIED: 对子View的尺寸不作限制,通常用于系统内部。
介绍完了我们来分析。getRootMeasureSpec()方法主要作用是在整个窗口的基础上计算出root view(顶层视图DecorView)的测量规格,相当于由Window和自身参数决定自己的measureSpec。该方法的两个参数分别表示:
�在这里我们看到,首先根据rootDimension来设置DecorView的测量模式。一般对于Activity来说,Window 是MATCH_PARENT,对于Dialog来说,Window 是WRAP_CONTENT。因此所以对于Activity分析,执行case 为MATCH_PARENT的代码,那么将设置DecorView的measureSpec的模式为EXACTLY+屏幕尺寸。设置完后,该方法返回。然后继续执行 performMeasure()方法。至此我们就要开始进行三大流程之一的测量流程。
一.Measure流程
Measure流程就是确定我们的View的大小,是全屏显示?还是具体大小等等。
我们来看看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);
}
}
在这里调用了mView.measure()方法,而mView就是指的decorView。
我们跟进去看看:
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
..//其他代码
//如果上一次的测量规格和这次不一样,那么重新测量大小
if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||
widthMeasureSpec != mOldWidthMeasureSpec ||
heightMeasureSpec != mOldHeightMeasureSpec) {
..//其他代码
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// measure ourselves, this should set the measured dimension flag back
----------代码1处--------------
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;
}
mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;
}
----------代码2处--------------
mOldWidthMeasureSpec = widthMeasureSpec;
mOldHeightMeasureSpec = heightMeasureSpec;
}
首先我们贴出关键代码,首先方法里会进行判断,如果当前的measureSpec和上次的不一样,那么说明需要进行测量。在代码1处执行了onMeasure()方法。没错,这个方法就是我们自定义View中经常重写的onMeasure()方法。代码2处是将当前设置的measureSpec赋值给mOldxxxMeasureSpec保存下。我们继续跟进去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;
}
传入的第一个参数为size,第二个measureSpec,这些都很简单。我们来看看代码,首先得到DecorView的测量模式和测量大小。然后根据测量模式进行处理。在前面我们已经知道decorView的测量模式为EXACTLY模式。因此这里直接返回DecorView之前的测量大小。
而如果是UNSPECIFIED模式,那么将传入的size返回。那么这个size是什么呢?我们回到之前调用getDefaultSize()的地方看看,发现size是由getSuggestedMinimumWidth()方法产生,我们再继续看看:
protected int getSuggestedMinimumWidth() {
return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
}
在这里看到是一个三目表达式用来获取View属性当中的最小值,也就是 android:minWidth和 android:minHeight的值,前提是View没有设置背景属性。如果设置了背景图,那么就在最小值和背景的最小值中间取最大值。
至此我们已经把参数相关的方法分析完了,参数设置完后调用setMeasuredDimension()方法即可完成测量。
至此我们就将默认实现的onMeasure()方法分析完了。
因为我们现在分析到DecorView的测量。所以我们来看看DecorView的测量。DecorView继承自FrameLayout。我们来看看FrameLayout的onMeasure()方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
..//其他代码
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
..//其他代码
}
去掉其他的代码,我们看到调用了父类的onMeasure(),我们跟进去看看FrameLayout的onMeasure()方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int count = getChildCount();
..//其他代码
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));
..//其他代码
}
我们贴出关键代码,可以看到首先是一个for循环遍历当前View的子View。然后如果需要测量所有子View并且这个子View可见。会调用measureChildWithMargins()方法来进行测量子View。我们跟进去看看:
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);
}
我们看到首先调用getChildMeasureSpec()方法来获取当前子View的measureSpec。然后调用measure()方法进行测量。我们先来看看getChildMeasureSpec()方法源码:
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
//得到父布局的测量模式和测量大小
int specMode = MeasureSpec.getMode(spec);
int specSize = MeasureSpec.getSize(spec);
//定义size变量,表示0和父类大小减去padding之间的最大值
//padding表示父布局的padding和当前子View的margin
//如果是求widthMeasureSpec,则是父布局的左右padding和左右margin,heightMeasure同理
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);
}
代码不算长,我们来看看。前面的变量说明已经在代码中给出。传入的childDimension在上面的代码中可以看出就是当前子View的LayoutParams的宽或者高。
然后根据是一段通过父类测量模式判断的switch方法。我们拿EXACTLY模式来看一下。如果父布局是EXACTLY模式,那么判断当前子View的宽度(假设当前方法是求widthMeasureSpec)是否大于0,如果大于0,那么结果就是子view的大小+ EXACTLY模式。如果子View的宽度是MATCH_PARENT,结果就是父类的大小+EXACTLY模式。如果子View的宽度是WRAP_CONTENT,结果就是父类的大小+ AT_MOST模式。另外两种情况就不再具体分析,读者自行查看即可。
注:上图来自任玉刚大神的《Android开发艺术探索》。
在得到当前子View的widthMeasureSpec和heightMeasureSpec后。调用child.measure(childWidthMeasureSpec, childHeightMeasureSpec)方法。然后又进行上面从measure()方法开始的流程。而我们上面分析onMeasure()方法是ViewGroup的,所以会通过循环测量所有的子View再进行自身的测量。
总结一下测量过程:
- View的measure方法是final类型的,子类不可以重写,子类可以通过重写onMeasure方法来测量自己的大小。
- View测量结束的标志是调用了setMeasuredDimension()方法,因此需要在自定义的View中重写onMeasure方法,在测量结束之前必须调用setMeasuredDimension方法测量才有效果。
- 在Activity生命周期onCreate()和onResume()方法中调用View.getMeasuredWidth()和View.getMeasuredHeight()返回值为0,因为DecorView添加到PhoneWindow窗口后才会开始测量所有View。而在Activity生命周期onCreate(),onResume()执行前performResumeActivity还未执行,因此调用View.getMeasuredHeight()返回值为0。
- 子视图View的大小是由父容器View和子视图View布局共同决定的。
二.Layout过程
上面我们分析完了测量流程,接下来我们分析Layout流程。Layout流程就是确定子View的摆放位置。比如应该摆放在父布局的左边?还是右边?等等这些问题。
接着本文最开始ViewRootImpl的performTraversals()方法的代码,执行完performMeasure()方法后,会接着执行performLayout()方法,我们去看看代码:
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
mLayoutRequested = false;
mScrollMayChange = true;
mInLayout = true;
final View host = mView;
..//其他代码
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
..//其他代码
mInLayout = false;
..//其他代码
}
我们看到调用了layout方法。而host就是DecorView。我们继续跟进去看看:
public void layout(int l, int t, int r, int b) {
..//其他代码
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;
}
首先将当前view旧的参数保存,然后定义了一个changed的布尔值,用来判断View的相关宽高是否和之前的一样。setOpticalFrame()方法里面还是调用了setFrame()方法,我们就重点来看setFrame()方法:
protected boolean setFrame(int left, int top, int right, int bottom) {
boolean changed = false;
..//其他代码
//如果有一条边的值和之前的不同,表示当前View的参数已修改
if (mLeft != left || mRight != right || mTop != top || mBottom != bottom) {
changed = true;
// Remember our drawn bit
int drawn = mPrivateFlags & PFLAG_DRAWN;
int oldWidth = mRight - mLeft;
int oldHeight = mBottom - mTop;
int newWidth = right - left;
int newHeight = bottom - top;
boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);
..//其他代码
mLeft = left;
mTop = top;
mRight = right;
mBottom = bottom;
mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);
if (sizeChanged) {
sizeChange(newWidth, newHeight, oldWidth, oldHeight);
}
..//其他代码
return changed;
}
贴出关键代码,我们可以看到,如果我们当前View的左右上下四条边中的一条发生了变化,那么就会执行if代码块里面的代码。将mLeft等四条边的值进行更新。而mLeft等四个成员变量就正式表示当前View的所处位置。在这里我们额外说明一下,我们经常在自定义View的时候使用getWidth()和getHeight()方法:
public final int getWidth() {
return mRight - mLeft;
}
public final int getHeight() {
return mBottom - mTop;
}
代码如上,因此我们在onMeasure()方法中调用得到结果为0的原因这是这样。因为这几个成员变量是在刚才的layout()方法中才变化。分析完了setFrame()方法,我们接着往下看layout()方法。接下来会调用onLayout()方法:
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
}
惊不惊喜??
意不意外??
居然是空实现??
没错,这是因此,系统并没有默认为我们实现onLayout(),而是由我们自由发挥。那我们去看看ViewGroup,看看它有没有实现onLayout()方法:
@Override
protected abstract void onLayout(boolean changed,
int l, int t, int r, int b);
居然是一个抽象方法。其实并不意外,我们自定义ViewGroup的时候,必须实现onLayout()方法的原因也在这里。
那我们去看看DecorView呢,它继承自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 */);
}
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();
//遍历所有子View
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
//如果子View的Visibility是GONE就不会设置,因此GONE的View是不会加载的
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确定child的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;
}
//通过这个switch确定child的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的mLeft等四条边
child.layout(childLeft, childTop, childLeft + width, childTop + height);
}
}
}
上面是FrameLayout的onLayout()方法,就只调用了一个layoutChildren()方法。具体解释已经在上面代码中。最后调用 child.layout(childLeft, childTop, childLeft + width, childTop + height)来重复之前的流程,我们就不再重复分析。
至此我们的layout流程也差不多分析完毕。来先用一张图总结一下。
- 真正确认View的布局是在layout方法里实现的,并不是在onLayout()这个方法里面。
- 必须在View布局完(也就是setFrame()方法)之后调用getHeight()和getWidth()方法获取到的View的宽高才大于0。
- ViewGroup的onLayout()方法是抽象的,因此我们自定义ViewGroup必须实现onLayout()方法。
至此我们就分析完了layout流程,我们继续接着分析最后一个步draw流程。
三.Draw
绘制流程通俗说就是将我们的View像画画一样将它们展现出来。
接着上面的performTraversals()方法,执行完了performMeasure(),performLayout()方法后,会接着执行performDraw()方法开开始绘制流程,我们来看看代码:
private void performDraw() {
..//其他代码
try {
draw(fullRedrawNeeded);
} finally {
mIsDrawing = false;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
..//其他代码
}
看到上面调用了draw()方法,我们继续跟进去:
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
boolean scalingRequired, Rect dirty) {
// Draw with software renderer.
final Canvas canvas;
try {
//从surface对象中获得canvas变量
canvas = mSurface.lockCanvas(dirty);
// If this bitmap's format includes an alpha channel, we
// need to clear it before drawing so that the child will
// properly re-composite its drawing on a transparent
// background. This automatically respects the clip/dirty region
// or
// If we are applying an offset, we need to clear the area
// where the offset doesn't appear to avoid having garbage
// left in the blank areas.
if (!canvas.isOpaque() || yoff != 0 || xoff != 0) {
canvas.drawColor(0, PorterDuff.Mode.CLEAR);
}
..//其他代码
try {
//调整画布的位置
canvas.translate(-xoff, -yoff);
if (mTranslator != null) {
mTranslator.translateCanvas(canvas);
}
canvas.setScreenDensity(scalingRequired ? mNoncompatDensity : 0);
attachInfo.mSetIgnoreDirtyState = false;
//调用View类中的成员方法draw开始绘制View视图
mView.draw(canvas);
}
..//其他代码
return true;
}
我们贴出关键代码看到,最后调用了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;
}
/*
* Here we do the full fledged routine...
* (this is an uncommon case where speed matters less,
* this is why we repeat some of the tests that have been
* done above)
*/
boolean drawTop = false;
boolean drawBottom = false;
boolean drawLeft = false;
boolean drawRight = false;
float topFadeStrength = 0.0f;
float bottomFadeStrength = 0.0f;
float leftFadeStrength = 0.0f;
float rightFadeStrength = 0.0f;
// Step 2, save the canvas' layers
int paddingLeft = mPaddingLeft;
final boolean offsetRequired = isPaddingOffsetRequired();
if (offsetRequired) {
paddingLeft += getLeftPaddingOffset();
}
int left = mScrollX + paddingLeft;
int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
int top = mScrollY + getFadeTop(offsetRequired);
int bottom = top + getFadeHeight(offsetRequired);
if (offsetRequired) {
right += getRightPaddingOffset();
bottom += getBottomPaddingOffset();
}
final ScrollabilityCache scrollabilityCache = mScrollCache;
final float fadeHeight = scrollabilityCache.fadingEdgeLength;
int length = (int) fadeHeight;
// clip the fade length if top and bottom fades overlap
// overlapping fades produce odd-looking artifacts
if (verticalEdges && (top + length > bottom - length)) {
length = (bottom - top) / 2;
}
// also clip horizontal fades if necessary
if (horizontalEdges && (left + length > right - length)) {
length = (right - left) / 2;
}
if (verticalEdges) {
topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
drawTop = topFadeStrength * fadeHeight > 1.0f;
bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
}
if (horizontalEdges) {
leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
drawLeft = leftFadeStrength * fadeHeight > 1.0f;
rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
drawRight = rightFadeStrength * fadeHeight > 1.0f;
}
saveCount = canvas.getSaveCount();
int solidColor = getSolidColor();
if (solidColor == 0) {
final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
if (drawTop) {
canvas.saveLayer(left, top, right, top + length, null, flags);
}
if (drawBottom) {
canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
}
if (drawLeft) {
canvas.saveLayer(left, top, left + length, bottom, null, flags);
}
if (drawRight) {
canvas.saveLayer(right - length, top, right, bottom, null, flags);
}
} else {
scrollabilityCache.setFadeColor(solidColor);
}
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Step 5, draw the fade effect and restore layers
final Paint p = scrollabilityCache.paint;
final Matrix matrix = scrollabilityCache.matrix;
final Shader fade = scrollabilityCache.shader;
if (drawTop) {
matrix.setScale(1, fadeHeight * topFadeStrength);
matrix.postTranslate(left, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
canvas.drawRect(left, top, right, top + length, p);
}
if (drawBottom) {
matrix.setScale(1, fadeHeight * bottomFadeStrength);
matrix.postRotate(180);
matrix.postTranslate(left, bottom);
fade.setLocalMatrix(matrix);
p.setShader(fade);
canvas.drawRect(left, bottom - length, right, bottom, p);
}
if (drawLeft) {
matrix.setScale(1, fadeHeight * leftFadeStrength);
matrix.postRotate(-90);
matrix.postTranslate(left, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
canvas.drawRect(left, top, left + length, bottom, p);
}
if (drawRight) {
matrix.setScale(1, fadeHeight * rightFadeStrength);
matrix.postRotate(90);
matrix.postTranslate(right, top);
fade.setLocalMatrix(matrix);
p.setShader(fade);
canvas.drawRect(right - length, top, right, bottom, p);
}
canvas.restoreToCount(saveCount);
// Step 6, draw decorations (scrollbars)
onDrawScrollBars(canvas);
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
}
view的draw()方法源码比较长,但是我们可以看到源码里的注释已经为我们解释清楚,绘制分为6步,第一步绘制背景,第二步如果需要的话,保存canvas的图层为了渐变效果做准备,第三步绘制自身内容,第四步绘制子View,第五部如果需要绘制渐变效果并且restore图层,第六步绘制装饰物,比如滚动条等。
其中第二步和第五步不是必须的。我们来看看第三步绘制自己内容和第四步绘制子View。
其中第三步调用了onDraw()方法,我们来看看:
protected void onDraw(Canvas canvas) {
}
我们看到这是一个空实现。其实也很容易理解。不同的View类型有自己不同的内容。因此在这里View这个父类是不能够一概而论的。因此这个onDraw()方法的逻辑需要具体的View去实现。正是这样,我们自定义View的时候都会重写onDraw()方法。
而第四步绘制子View的时候调用了dispatchDraw()方法,我们跟进去看看:
protected void dispatchDraw(Canvas canvas) {
}
dispatchDraw()也是一个空实现。其实这也很容易理解。绘制子View也只有ViewGroup类型的控件才会有子View,因此在View类中并没有具体的实现逻辑。我们去ViewGroup中看看dispatchDraw()方法:
@Override
protected void dispatchDraw(Canvas canvas) {
boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
final int childrenCount = mChildrenCount;
final View[] children = mChildren;
int flags = mGroupFlags;
//判断当前ViewGroup容器是否设置了布局动画,如果有,那么遍历所有子View,设置布局动画
if ((flags & FLAG_RUN_ANIMATION) != 0 && canAnimate()) {
final boolean buildCache = !isHardwareAccelerated();
for (int i = 0; i < childrenCount; i++) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) == VISIBLE) {
final LayoutParams params = child.getLayoutParams();
attachLayoutAnimationParameters(child, params, i, childrenCount);
bindLayoutAnimation(child);
}
}
final LayoutAnimationController controller = mLayoutAnimationController;
if (controller.willOverlap()) {
mGroupFlags |= FLAG_OPTIMIZE_INVALIDATE;
}
//开始布局动画
controller.start();
mGroupFlags &= ~FLAG_RUN_ANIMATION;
mGroupFlags &= ~FLAG_ANIMATION_DONE;
//设置动画监听
if (mAnimationListener != null) {
mAnimationListener.onAnimationStart(controller.getAnimation());
}
}
int clipSaveCount = 0;
//判断是否需要裁剪边缘
final boolean clipToPadding = (flags & CLIP_TO_PADDING_MASK) == CLIP_TO_PADDING_MASK;
if (clipToPadding) {
clipSaveCount = canvas.save();
canvas.clipRect(mScrollX + mPaddingLeft, mScrollY + mPaddingTop,
mScrollX + mRight - mLeft - mPaddingRight,
mScrollY + mBottom - mTop - mPaddingBottom);
}
//遍历子View,绘制子View
for (int i = 0; i < childrenCount; i++) {
while (transientIndex >= 0 && mTransientIndices.get(transientIndex) == i) {
final View transientChild = mTransientViews.get(transientIndex);
if ((transientChild.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
transientChild.getAnimation() != null) {
//调用drawChild()方法
more |= drawChild(canvas, transientChild, drawingTime);
}
transientIndex++;
if (transientIndex >= transientCount) {
transientIndex = -1;
}
}
..//其他代码
}
我们可以看到上面的源码,大概解释已经在代码中,其中在遍历绘制子View的时候调用了drawChild()方法,我们进去看看:
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
return child.draw(canvas, this, drawingTime);
}
这里可以看到,就是调用了子View的draw()方法。至此就又进去了子View的draw()方法,又进行我们上面的分析过程。我们就不再重复解释。
整个绘制的过程就已经基本分析完毕,那么我们来总结一下:
最开始ViewRootImpl的performDraw()调用了ViewRootImpl的draw()方法,里面调用了ViewRootImpl的drawSoftware()方法,又调用了mView的draw()方法(mView就是DecorView,是一个ViewGroup),draw里面分为4步,绘制背景,绘制自己,绘制子View,绘制修饰物。其中第二步中onDraw()方法View类中默认是空实现,所以需要自己实现,第三步中绘制子View的dispatchDraw()方法中View类默认为空实现。ViewGroup实现了它,在里面循环调用了所有子View的draw()方法。
View类中onDraw()和dispatchDraw()方法为空实现,因为onDraw()是需要具体的View绘制自己的UI,所以不会提供默认实现。dispatchDraw()也因为是ViewGroup类型的才会控制绘制子View,所以View类没有默认实现,只有ViewGroup类才重写。
至此我们View的绘制的三个大流程已经基本分析完毕,其中还有很多细节的地方没有分析到,如果读者感兴趣可以自己探索。同时要感谢网上大神的各种分享资料才弄懂很多东西。