在Android开发中,如果你想了解一个View的工作原理或者你想根据需求自定义View ,那么View的Measure,Layout,draw三大流程是你是怎么也绕不开的。在正式介绍View的三大流程之前,我们必须先介绍一些基本概念,这样才能更好的理解View的measure、layout、draw三个过程。
本文涉及到内容
ViewRoot——三大流程的开始
ViewRoot对应于源码中的ViewRootImpl类,它是连接WIndowManager和DecorView的 纽带,View的三大流程都是通过ViewRootImpl来完成的。ViewRootImp的创建是在WindowManagerGlobal类的addView()方法中,具体源码:
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
if (view == null) {
throw new IllegalArgumentException("view must not be null");
}
if (display == null) {
throw new IllegalArgumentException("display must not be null");
}
if (!(params instanceof WindowManager.LayoutParams)) {
throw new IllegalArgumentException("Params must be WindowManager.LayoutParams");
}
final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;
if (parentWindow != null) {
parentWindow.adjustLayoutParamsForSubWindow(wparams);
} else {
// If there's no parent, then hardware acceleration for this view is
// set from the application's hardware acceleration setting.
final Context context = view.getContext();
if (context != null
&& (context.getApplicationInfo().flags
& ApplicationInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
wparams.flags |= WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED;
}
}
ViewRootImpl root;
View panelParentView = null;
synchronized (mLock) {
// Start watching for system property changes.
if (mSystemPropertyUpdater == null) {
mSystemPropertyUpdater = new Runnable() {
@Override public void run() {
synchronized (mLock) {
for (int i = mRoots.size() - 1; i >= 0; --i) {
mRoots.get(i).loadSystemProperties();
}
}
}
};
SystemProperties.addChangeCallback(mSystemPropertyUpdater);
}
int index = findViewLocked(view, false);
if (index >= 0) {
if (mDyingViews.contains(view)) {
// Don't wait for MSG_DIE to make it's way through root's queue.
mRoots.get(index).doDie();
} else {
throw new IllegalStateException("View " + view
+ " has already been added to the window manager.");
}
// The previous removeView() had not completed executing. Now it has.
}
// If this is a panel window, then find the window it is being
// attached to for future reference.
if (wparams.type >= WindowManager.LayoutParams.FIRST_SUB_WINDOW &&
wparams.type <= WindowManager.LayoutParams.LAST_SUB_WINDOW) {
final int count = mViews.size();
for (int i = 0; i < count; i++) {
if (mRoots.get(i).mWindow.asBinder() == wparams.token) {
panelParentView = mViews.get(i);
}
}
}
root = new ViewRootImpl(view.getContext(), display);
view.setLayoutParams(wparams);
mViews.add(view);
mRoots.add(root);
mParams.add(wparams);
// do this last because it fires off messages to start doing things
try {
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
// BadTokenException or InvalidDisplayException, clean up.
if (index >= 0) {
removeViewLocked(index, true);
}
throw e;
}
}
}
View的绘制流程是从ViewRoot的performTraversals()方法开始,经过三大流程将View绘制出来,其中measure用来测量View的宽高,layout用来确定View在父布局中的位置,draw负责将View绘制在屏幕上。
针对performTraversals的大致流程如下:
performTraversals依次调用performMeasure,performLayout,performDraw方法完成顶层view的绘制,onMeasure,onLayout,onDraw三个方法中会对调用子View的相关流程,完成所有子View的绘制流程。
Measure过程决定了View的宽高,Measure过程完成以后,可以通过getMeasureWidth和getMeasureHeight获取view的测量宽高,在绝大部分情况下,测量宽高就等于view的最终宽高。layout过程决定了view的四个顶点的坐标和View最终的宽高,完成以后可以通过getWidth/getHeight方法获取view的最终宽高。Draw过程决定了View的显示,只有Draw过程完成以后,View的内容才会呈现在屏幕上。
DecorView——最顶层的View
DecorView是FrameLayout的子类,它被认为是Android视图树的根节点视图。DecorView作为顶级View,一般情况下它内部包含一个竖直方向的LinearLayout。其与Activity,window的关系如下图:
DecorView的创建是在PhoneWindow的installDecor()方法中,这里摘取installDecor的部分代码:
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
mDecor = generateDecor(-1);
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
} else {
mDecor.setWindow(this);
}
DecorView 是通过generateDecor()得到的,以下是generateDecor的源码
protected DecorView generateDecor(int featureId) {
// System process doesn't have application context and in that case we need to directly use
// the context we have. Otherwise we want the application context, so we don't cling to the
// activity.
Context context;
if (mUseDecorContext) {
Context applicationContext = getContext().getApplicationContext();
if (applicationContext == null) {
context = getContext();
} else {
context = new DecorContext(applicationContext, getContext());
if (mTheme != -1) {
context.setTheme(mTheme);
}
}
} else {
context = getContext();
}
return new DecorView(context, featureId, this, getAttributes());
}
MeasureSpec
在view的三大流程中,测量的过程是比较复杂的,为了更好地理解view的Measure过程,我们需要先弄清楚MeasureSpec。
MeasureSpec代表一个32位的Int值,高两位代表SpecMode,SpecMode是值测量模式,剩下的30位代表SpecSize,SpecSize是指在某种测量模式下的大小。通过一个Int值避免了过多的内存对象分配,方便操作。
通过源码,我们可以看出MeasureSpec定义了三种SpecMode:
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 {}
/**
* Measure specification mode: The parent has not imposed any constraint
* on the child. It can be whatever size it wants.
*/
public static final int UNSPECIFIED = 0 << MODE_SHIFT;
/**
* Measure specification mode: The parent has determined an exact size
* for the child. The child is going to be given those bounds regardless
* of how big it wants to be.
*/
public static final int EXACTLY = 1 << MODE_SHIFT;
/**
* Measure specification mode: The child can be as large as it wants up
* to the specified size.
*/
public static final int AT_MOST = 2 << MODE_SHIFT;
(1)UNSPECIFIEND
父容易不对 View 有任何影响,要多大给多大,这种情况一般用于系统内部。
(2)EXACTLY
父容器已经检测出 View 所需要的精确大小,这个时候 View 的最终大小就是 MeasureSpec 所指定的值,它对应于 LayoutParams 的 match_parent 和具体的数值两种模式。
(3)AT_MOST
父容器指定一个大小即 SpecSize,View 的大小不能大于这个值,具体是什么值要看不同 View 的具体实现,它对应于 LayoutParams 的warp_content。
MeasureSpec类中还提供生成MeasureSpec的方法及获取SpecMode和SpecSize的方法。
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);
}
}
/**
* Extracts the mode from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the mode from
* @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
* {@link android.view.View.MeasureSpec#AT_MOST} or
* {@link android.view.View.MeasureSpec#EXACTLY}
*/
@MeasureSpecMod
public static int getMode(int measureSpec) {
//noinspection ResourceType
return (measureSpec & MODE_MASK);
}
/**
* Extracts the size from the supplied measure specification.
*
* @param measureSpec the measure specification to extract the size from
* @return the size in pixels defined in the supplied measure specification
*/
public static int getSize(int measureSpec) {
return (measureSpec & ~MODE_MASK);
}
View MeasureSpec 和LayoutParams关系
系统内部是通过MeasureSpec来给View 进行测量工作的,但是我们实际却是只用LayoutParams来设置的.这里我们就是分析2者直接的联系。
其实View在测量的时候,系统会将LayoutParams在父容器的约束下转换成对应的MeasureSpec,然后根据这个MeasureSpec来确定View测量之后的高和宽.也就是说MeasureSpec不是由LayoutParams唯一确定的,而是要和父容器一起来确定的.而且普通的View和页面的顶级View(DecorView)的MeasureSpec的转换过程是有些不同的。
DecorView的MeasureSpec是由窗口的尺寸和DecorView其自身的LayoutParams来共同决定的。普通View的MeasureSpec是由父容器的MeasureSpec和普通View自身的LayoutParams来共同决定的。
对于DecorView来说,在VIewRootImp中measureHierarchy方法中有如下代码,展示了decorView的MeasureSpec创建过程:
childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width); childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height); performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
其中,baseSize是基于当前DisplayMetrics进行转换,获取的指定资源id对应的尺寸,desiredWindowHeight是屏幕高度。
下面是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;
}
通过上面代码,我们可以看出,DecorView的MeasureSpec的产生遵循以下规则:
1.LayoutParams.MATCH_PARENT:
SpecSize=windowSize, SpecMode=MeasureSpec.EXACTLY
2.LayoutParams.WRAP_CONTENT:
SpecSize=windowSize, SpecMode=MeasureSpec.AT_MOST
3.固定大小:
SpecSize=rootDimension, SpecMode=MeasureSpec.EXACTLY
其他View的MeasureSpec创建过程与DecorView类似,与其父容器的MeasureSpec和其自身的LayoutParams有关,具体关系表格:
了解了view三大流程的开始——ViewRootImp和最顶层viewDecorView,我们对view的流程的有了大致的了解。下一篇将详细介绍view的三大流程。理解了MeasureSpec和MeasureSpec与自身LayoutParams关系之后,我们接下来理解View的Measure过程就好理解了。