不忘初心 砥砺前行, Tomorrow Is Another Day !html
本文概要:java
如无特别说明,本次源码版本均基于8.0.bash
在平常开发咱们在Activity的OnCreate中经过setContentView设置自定义布局时,实际上调用了PhoneWindow的setContentView方法,在此方法里面首先会初始化一个DecorView.最后将咱们自定义布局加载到DecorView布局中id为content的FrameLayout.app
为了证明上述结论的正确性,咱们能够参考源码.iview
对应源码ide
//Activity.java
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
//PhoneWindow.java
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
/**
* 1.初始化DecorView
*/
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
/*
*2.解析layoutResID布局文件,将它嵌入到*mContentParent的内部
*/
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
//PhoneWindow#installDecor方法
private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
//1.生成DecorView
mDecor = generateDecor(-1);
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
}
} else {
mDecor.setWindow(this);
}
if (mContentParent == null) {
//2.找到ID为content的ViewGroup
mContentParent = generateLayout(mDecor);
// Set up decor part of UI to ignore fitsSystemWindows if appropriate.
mDecor.makeOptionalFitsSystemWindows();
final DecorContentParent decorContentParent = (DecorContentParent) mDecor.findViewById(
R.id.decor_content_parent);
//...省略部分代码
}
}
复制代码
咱们知道ActivityThread做为启动入口,会经过handleLaunchActivity,建立一个Activity对象.其中在performLaunchActivity中调用OnCreate方法,也就是上一节所讲内容.接着在handleResumeActivity方法里,开始将View加载到Window最后.这里咱们只看与View绘制相关流程.布局
1. 首先经过WindowManager将DecorView添加到Window中,与此同时将ViewRootImpl对象经过setView将DecorView关联起来.post
对应源码学习
//WindowManagerImpl.java
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
//调用WindowManagerGlobal的addView
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}
//WindowManagerGlobal.java
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
//...省略部分代码
ViewRootImpl root;
View panelParentView = null;
synchronized (mLock) {
//...省略部分代码
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 {
//将DecorView关联起来
root.setView(view, wparams, panelParentView);
} catch (RuntimeException e) {
// BadTokenException or InvalidDisplayException, clean up.
if (index >= 0) {
removeViewLocked(index, true);
}
throw e;
}
}
}
复制代码
2. 在加载到Window以前,其ViewRootImpl内部会经过requestLayout方法来布局整个DecorView树,最终调用performTravels,依次执行DecorView的measure、layout、draw三大过程.动画
对应源码
//ViewRootImpl.java
@Override
public void requestLayout() {
if (!mHandlingLayoutInLayoutRequest) {
checkThread();
mLayoutRequested = true;
//执行开始布局
scheduleTraversals();
}
}
private void performTraversals() {
//...省略部分代码
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
//...省略部分代码
performLayout(lp, mWidth, mHeight);
//...省略部分代码
performDraw();
//...省略部分代码
}
复制代码
了解了相关启动加载与绘制流程后,下面就开始进入正题-View相关的重要知识点.
MeasureSpec能够理解为规格限制,其由specSize和specMode构成.
提供相应的打包与拆包方法: makeMeasureSpec/getMode,getSize
Mode 三种模式:
MeasureSpec 的计算方式:
对于DecorView,它的MeasureSpec由窗口与自身的layoutParams共同决定---在viewRootImpl完成.
对于普通View,它的MeasureSpec由父容器的MeasureSpec与自身的layoutParams共同决定---在父容器中完成.
对应源码:
//ViewRootImpl.java
private static int getRootMeasureSpec(int windowSize, int rootDimension) {
int measureSpec;
switch (rootDimension) {
case ViewGroup.LayoutParams.MATCH_PARENT:
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
break;
case ViewGroup.LayoutParams.WRAP_CONTENT:
measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
break;
default:
measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
break;
}
return measureSpec;
}
//ViewGroup.java
protected void measureChildWithMargins(View child,
int parentWidthMeasureSpec, int widthUsed,
int parentHeightMeasureSpec, int heightUsed) {
final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();
//对于在父元素的已占用的空间=父元素自身padding+子元素的magrgin
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);
}
/** @param 父元素的MeasureSpec
* @param 对于在父元素的已占用的空间=父元素自身padding+子元素的magrgin
* @param 自身的lp参数
* @return 子元素的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) {
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) {
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);
}
复制代码
对于上述源码咱们重点注意getChildMeasureSpec方法,其中第二个参数表明的是父元素已占用的空间.该方法体现了生成普通View的MeasureSpec的规格.
遵循如下规则,UNSPECIFIED除外.前者表示子元素的layoutParams参数.
从上面规则能够发现,不管是match_parent,仍是wrap_content,最终返回的大小都是parentSize,也就是父元素的可用空间.而View在默认测量时getDefaultSize会直接返回该大小,因此在测量过程当中,须要对wrap_content进行特殊处理.具体如何处理下一篇在讲解.
measure、layout、draw 是调度方法,由父容器调用,进行预处理.
在测量以前父元素都须要生成对应子view的测量规格MeasureSpec.具体见上一节.
做用: 肯定测量宽高
measure-onMeasure-setMeasureDimension
复制代码
onMeasure 实际测量方法
对应源码
//View.java
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//获取默认值并保存
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
//获取默认值
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;//直接返回父元素可用空间,因此须要对wrap_content作特殊处理.
break;
}
return result;
}
//ViewGroup.java
protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
final int size = mChildrenCount;
final View[] children = mChildren;
//遍历全部的子View
for (int i = 0; i < size; ++i) {
final View child = children[i];
if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
measureChild(child, widthMeasureSpec, heightMeasureSpec);
}
}
}
protected void measureChild(View child, int parentWidthMeasureSpec,
int parentHeightMeasureSpec) {
final LayoutParams lp = child.getLayoutParams();
//得到子View的MeasureSpec
final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
mPaddingLeft + mPaddingRight, lp.width);
final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
mPaddingTop + mPaddingBottom, lp.height);
//调用ziview的measure方法
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
复制代码
做用: 肯定最终宽高和位置
layout-onLayout
复制代码
layout 保存传入的位置,肯定了View自己在其父View中的位置.
若是子View是纯View,那么在onLayout里,什么都不作.
若是是ViewGroup,那么在onLayout里,首先须要遍历调用全部子view的layout方法,让子View完成自我布局,依次递归.
对应源码
@SuppressWarnings({"unchecked"})
public void layout(int l, int t, int r, int b) {
//...省略部分代码
int oldL = mLeft;
int oldT = mTop;
int oldB = mBottom;
int oldR = mRight;
//setFrame设置View四个顶点位置,肯定在父容器的位置
boolean changed = isLayoutModeOptical(mParent) ?
setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
//开始布局子view位置.
onLayout(changed, l, t, r, b);
if (shouldDrawRoundScrollbar()) {
if(mRoundScrollbarRenderer == null) {
mRoundScrollbarRenderer = new RoundScrollbarRenderer(this);
}
} else {
mRoundScrollbarRenderer = null;
}
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);
}
}
}
//...省略部分代码
}
复制代码
从测量与布局两个阶段能够看出两个特色.
做用: 绘制到屏幕上
draw方法里流程
因为本人技术有限,若有错误的地方,麻烦你们给我提出来,本人不胜感激,你们一块儿学习进步.
参考连接: