安卓view的绘制流程主要分为三个阶段:
一、测量过程(mesure)
二、确定子元素的过程(layout)
三、绘制过程(draw)
我们在activity的oncread方法中会使用setContentView来填充一个布局
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID); initWindowDecorActionBar();
}
这个getWindow方法是获取的PhoneWindow,然后调用它的setContentView方法,在此方法中,会调用generateDecor()方法,方法体如下:
protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}
在此方法中会实例化一个decorview的东西,那么它是什么东西呢?其实decorview是整个view树的最顶层view,有一个子LinearLayout,代表整个Window界面,包含通知栏,标题栏,内容显示栏三块区域,我们setcontentview的布局就是这个内容区域,所以说,DecorView是我们的顶层布局。
到此,我们已经 加载了布局,但是还没有经过测量等的步骤,所以还无法显示布局界面,接下来安卓需要做的是把decorview加载到window,并且进行测量等工作。
那么decorview是如何加载到window中呢?
在activity创建的时候,UI线程会调用handleResumeActivity方法,此方法中会获取该activity所关联的window,DecorView和windowManager,具体代码如下:
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
if (a.mVisibleFromClient) {
a.mWindowAdded = true; wm.addView(decor, l);
}
windowManager的实现类中,会实例化一个ViewRootImpl的类,此时会把decorview传入ViewRootImpl对象,代码如下:
root = new ViewRootImpl(view.getContext(), display);
root.setView(view, wparams, panelParentView);
在setview方法中,会调用WindowManagerService将decorview添加到window中,然后WindowManagerService调用ViewRootImpl的performTraverals方法开始进行测量、布局、绘制流程,可以说,现在才真正开始绘制布局,ViewRootImpl是连接WindowManager和DecorView的桥梁,测量、布局、绘制都是通过ViewRootImpl来进行的。
ViewRootImpl和MeasureSpec
我们通过查看ViewRootImpl类发现,此类有7511行代码,我们挑重点看,
mesure、layout、draw的发起者都是performTraversals方法,接下来我们来查看下此方法的代码:
if (!mStopped || mReportNextDraw) {
boolean focusChangedDueToTouchMode = ensureTouchModeLocally(
(relayoutResult&WindowManagerGlobal.RELAYOUT_RES_IN_TOUCH_MODE) != 0);
if (focusChangedDueToTouchMode || mWidth != host.getMeasuredWidth()
|| mHeight != host.getMeasuredHeight() || contentInsetsChanged ||
updatedConfiguration) {
int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);
int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);
......
// Ask host how big it wants to be
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
......
if (measureAgain) {
......
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
}
layoutRequested = true;
}
}
} else {
......
}
//performLayout
if (didLayout) {
performLayout(lp, mWidth, mHeight);
......
}
//performDraw
if (!cancelDraw && !newSurface) {
if (mPendingTransitions != null && mPendingTransitions.size() > 0) {
for (int i = 0; i < mPendingTransitions.size(); ++i) {
mPendingTransitions.get(i).startChangingAnimations();
}
mPendingTransitions.clear();
}
performDraw();
} else {
......
}
通过以上代码可以发现childWidthMeasureSpec和childHeightMeasureSpec 两个属性,这两个数是一个32位的整型数,高2位表示的是测量模式,剩余30位表示的是对应测量模式下的大小。
我们去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是View里的一个静态内部类:
public static class MeasureSpec {
private static final int MODE_SHIFT = 30;
private static final int MODE_MASK = 0x3 << MODE_SHIFT;
/** @hide */
@IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
@Retention(RetentionPolicy.SOURCE)
public @interface MeasureSpecMode {}
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(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
@MeasureSpecMode int mode) {
if (sUseBrokenMakeMeasureSpec) {
return size + mode;
} else {
return (size & ~MODE_MASK) | (mode & MODE_MASK);
}
}
public static int makeSafeMeasureSpec(int size, int mode) {
if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
return 0;
}
return makeMeasureSpec(size, mode);
}
@MeasureSpecMode
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
static int adjust(int measureSpec, int delta) {
final int mode = getMode(measureSpec);
int size = getSize(measureSpec);
if (mode == UNSPECIFIED) {
// No need to adjust size for UNSPECIFIED mode.
return makeMeasureSpec(size, UNSPECIFIED);
}
size += delta;
if (size < 0) {
Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
") spec: " + toString(measureSpec) + " delta: " + delta);
size = 0;
}
return makeMeasureSpec(size, mode);
}
public static String toString(int measureSpec) {
int mode = getMode(measureSpec);
int size = getSize(measureSpec);
StringBuilder sb = new StringBuilder("MeasureSpec: ");
if (mode == UNSPECIFIED)
sb.append("UNSPECIFIED ");
else if (mode == EXACTLY)
sb.append("EXACTLY ");
else if (mode == AT_MOST)
sb.append("AT_MOST ");
else
sb.append(mode).append(" ");
sb.append(size);
return sb.toString();
}
}
可以看到,它有三种测量模式,UNSPECIFIED,EXACTLY和AT_MOST,三种模式分别代表的含义:
UNSPECIFIED:不指定测量模式,父视图没有限制子视图的大小,子视图可以使想要的任何尺寸,通常这个模式在开发中用不到,日常开发中,必然会根据父视图去限制子视图的大小
EXACTLY:精确测量模式,当该视图的宽高指定为确定数值或者match_parent时生效,表示父视图已经决定了子视图的大小,测量出来的值其实就是设置的数值
AT_MOST:最大值模式,当该视图的宽高为wrap_content时生效,此时只要子视图的尺寸在父视图允许的最大范围都可以,常见的情况比如:需要在ScrollView中嵌套ListView,此时如果不重写listview的测量模式为AT_MOST,则会出现listview只显示一行的情况
至此,测量之前的工作基本分析完毕。
View的Measure过程
现在我们开始进行mesure的过程,查看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的mesure方法,这个mview是WindowManager中实例化ViewRootImpl后调用setView传进来的DecorView,所以说,测量是通过父View往子View进行的过程
接下来看下ViewGroup中是怎么把measure分发给各个子View的:
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);
}
}
}
以上代码很容易理解,用循环的方式挨个measureChild来进行的,继续看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获取childWidthMeasureSpec 和childHeightMeasureSpec 后,继续调用自身的measure方法,我们继续跟踪,在view的measure方法中,有如下一个方法:
onMeasure(widthMeasureSpec, heightMeasureSpec);
由于view的measure为final方法,所以当我们自定义控件时,系统为我们准备都得覆盖方法就是上边的onMeasure方法,onMeasure里有两行代码:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
setMeasuredDimension用于设置View测量的宽和高,getDefaultSize表示,如果View没有重新onmeasure方法,则会直接获取默认的宽和高,这里把getDefaultSize当作参数直接传给setMeasuredDimension,就是为了防止view没有重写onMeasure方法。
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;
}
至此,测量的基本流程已进行完毕,由于layout和draw过程相对简单,本篇将不再讨论
共同学习,写下你的评论
评论加载中...
作者其他优质文章