一、问题:
首先还是来看一种情况,我们在Activity的三个地方查看View的measureHeight属性,因为只有measure后的View才具有measureHeight属性,否则为0,
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mHandle = Handler(Looper.getMainLooper())
Log.d("MainActivity", "onCreate btn_view.measuredHeight ==> " + btn_view.measuredHeight.toString())
btn_view.post {
Log.d("MainActivity", "post btn_view.measuredHeight ==> " + btn_view.measuredHeight.toString())
}
}
override fun onResume() {
super.onResume()
Log.d("MainActivity", "onResume btn_view.measuredHeight ==> " + btn_view.measuredHeight.toString())
}
我们再看一下log
2020-10-13 10:22:26.067 22953-22953/? D/MainActivity: onCreate btn_view.measuredHeight ==> 0
2020-10-13 10:22:26.074 22953-22953/? D/MainActivity: onResume btn_view.measuredHeight ==> 0
2020-10-13 10:22:26.233 22953-22953/? D/MainActivity: post btn_view.measuredHeight ==> 144
这里显示,只有View.post()里面,才打印出了View的measureHeight属性,这就说明,在onCreate方法和onResume方法执行时,我们的View都还没被measure
二、onCreate()方法、onResume()方法
之前我们分析过,setContentView的源码,为了看仔细一点,我们选择看继承Avtivity的setContentView的源码,而Activity里面的setContentView是调用的PhoneWindow的setContentView,所以PhoneWindow的setContentView
public void setContentView(int layoutResID) {
if (mContentParent == null) {
//创建DecorView和mContentParent
//并将我们系统的布局android.R.layout.content添加到了mDecor上
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 {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
//...
}
这里的setContent只是创建了DecorView并把我们的布局添加到了DecorView上,但是还没有调用onMeasure方法。
我们再从Activity的启动流程入手,对于ActivityThread里面的performLaunchActivity方法,它里面通过反射调用了Activity的onCreate方法
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//...
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
//...
}
而ActivityThread的handleResumeActivity方法,他里面调用了performResumeActivity方法
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
//...
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
//...
if (r.window == null && !a.mFinished && willBeVisible) {
ViewManager wm = a.getWindowManager();
//...
View decor = r.window.getDecorView();
if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
wm.addView(decor, l);
}
}
}
if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
//...
if ((l.softInputMode
& WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
!= forwardBit) {
if (r.activity.mVisibleFromClient) {
ViewManager wm = a.getWindowManager();
View decor = r.window.getDecorView();
wm.updateViewLayout(decor, l);
}
}
if (r.activity.mVisibleFromClient) {
r.activity.makeVisible();
}
}
}
performResumeActivity里面调用了performResume,这里才去执行了我们Activity的onResume方法,
public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
String reason) {
try {
r.activity.performResume(r.startsNotResumed, reason);
}catch (Exception e) {
//...
}
}
handleResumeActivity方法里面调用完performResumeActivity之后,才调用的wm.addView(decor, l);,,他是从这里才把DecorView加载到ViewManager里面,这时才开始View的绘制流程:measure() -> layout() -> draw()
所以,这里就解释了,为什么我们在onCreate()和onResume()里面获取不到View的measureHeight属性,就是因为onCreate和obResume方法执行的时候,View的绘制还没开始。而View.post()里面为什么就可以了呢?
三、View.post()方法
我们看一下View.post的源码
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
getRunQueue().post(action);
return true;
}
这里可以看到,post进来之后,他是调用的HandlerActionQueue.java类里面的post方法
public void post(Runnable action) {
postDelayed(action, 0);
}
public void postDelayed(Runnable action, long delayMillis) {
final HandlerAction handlerAction = new HandlerAction(action, delayMillis);
synchronized (this) {
if (mActions == null) {
mActions = new HandlerAction[4];
}
//入队列
mActions = GrowingArrayUtils.append(mActions, mCount, handlerAction);
mCount++;
}
}
post进来之后的cation会保存进队列中,但是没有执行,而是在View的dispatchAttachedToWindow方法中执行,而dispatchAttachedToWindow方法就是在测量完毕之后才调用的
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
//...
// Transfer all pending runnables.
if (mRunQueue != null) {
//里面是个for循环,去执行队列中的全部Action
mRunQueue.executeActions(info.mHandler);
mRunQueue = null;
}
}
所以,到了这里,我们也就基本解释清楚了,为什么onCreate、onResume和View.post里面获取View的measureHeight属性出现的情况了。
四、总结(过程展示)
执行过程:
image-20201013162709179.png五、WindowManagerImpl
我们在ActivityThread的handleResumeActivity()方法中,看到了他内部调用了ViewManager的addView()和updateViewLayout()的方法,而ViewManager的这两个方法是在他的实现类WindowManagerImpl里面实现的
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
//...
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
//...
ViewManager wm = a.getWindowManager();
View decor = r.window.getDecorView();
if(){
wm.addView(decor, l);
}else{
wm.updateViewLayout(decor, l);
}
}
我们进到WindowManagerImpl类中,他调用的是mGlobal的方法
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mContext.getDisplayNoVerify(), mParentWindow,
mContext.getUserId());
}
@Override
public void updateViewLayout(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.updateViewLayout(view, params);
}
再往里面进去
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow, int userId) {
//...
ViewRootImpl root;
View panelParentView = null;
//实例化了ViewRootImpl的对象root
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, userId);
} catch (RuntimeException e) {
// BadTokenException or InvalidDisplayException, clean up.
if (index >= 0) {
removeViewLocked(index, true);
}
throw e;
}
}
从这里我们发现一个事情,我们以前一直以为DecorView就是PhoneWindow下面的根布局,但是从这里,我们可以看到,DecorView也是加到ViewRootImpl上面的root.setView(view, wparams, panelParentView, userId);
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView,
int userId) {
//...
requestLayout();
//...
}
public void requestLayout() {
//...
scheduleTraversals();
}
void scheduleTraversals() {
//...
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
//...
}
final class TraversalRunnable implements Runnable {
@Override
public void run() {
doTraversal();
}
}
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
void doTraversal() {
//...
performTraversals();
//...
}
终于,我们追到了performTraversals()方法,网上很多文章,也就是从这里开始讲的
六、重点:View的绘制流程
private void performTraversals() {
getRunQueue().executeActions(mAttachInfo.mHandler);
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
performLayout(lp, mWidth, mHeight);
performDraw();
}
1. 绘制流程第一步performMeasure
ViewRootImpl.java
private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
try {
mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
在View.java中查看measure方法
public final void measure(int widthMeasureSpec, int heightMeasureSpec) {
if (cacheIndex < 0 || sIgnoreMeasureCache) {
// measure ourselves, this should set the measured dimension flag back
//调用View里面的onMeasure方法,测量开始
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;
}
}
这个方法里面调用了onMeasure方法,而此时onMeasure测量的是我们的根布局DecorView方法,测量了DecorView后,我们又会用onMeasure测量我们布局的根布局(这里以LinearLayout为例)
LinearLayout.java
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
//首先判断的是orientation
if (mOrientation == VERTICAL) {
measureVertical(widthMeasureSpec, heightMeasureSpec);
} else {
measureHorizontal(widthMeasureSpec, heightMeasureSpec);
}
}
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//通过for循环去拿我们里面的子布局
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
heightMeasureSpec, usedHeight);
}
//测量完之后,接着调用这个方法,我们的布局才有了真正的宽和高,这里进去是给measuredWidth和measuredHeight赋值
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
}
void measureChildBeforeLayout(View child, int childIndex,
int widthMeasureSpec, int totalWidth, int heightMeasureSpec,
int totalHeight) {
measureChildWithMargins(child, widthMeasureSpec, totalWidth,
heightMeasureSpec, totalHeight);
}
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);
//通过调用子View的onMeasure方法,去测量子View的宽高,这里的两个参数childXXXMeasureSpec都是父布局已经给我们测量好了的
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
ViewGroup.java里面查看测量的方式getChildMeasureSpec()方法
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;
//根据父布局的模式去给子View的resultSize、resultMode赋值
switch (specMode) {
// Parent has imposed an exact size on us
//当父布局是match_parent、fill_parent(Deprecated)、明确的值
case MeasureSpec.EXACTLY:
if (childDimension >= 0) {//当ViewGroup中的子view是设置了具体大小的值时( X dp)
//子View的大小就等于设置的子View的大小
resultSize = childDimension;
//mode就是EXACTLY
resultMode = MeasureSpec.EXACTLY;
} else if (childDimension == LayoutParams.MATCH_PARENT) {//如果子View外面设置的大小是MATCH_PARENT
// Child wants to be our size. So be it.
//子View的大小就等于父布局的大小
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
//当父布局是warp_content时
case MeasureSpec.AT_MOST:
if (childDimension >= 0) {
// Child wants a specific size... so be it
resultSize = childDimension;
//子View被设置成了明确的值,那么他的模式直接就是EXACTLY,不受父布局的影响
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;
//当父布局是AT_MOST模式时,即使子View是MATCH_PARENT,他的模式,最终还是AT_MOST,所以,子View的mode是父布局的mode和自己一起决定的
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);
}
调用完measure方法之后,就会调用setMeasuredDimension()方法,这个时候我们的布局才真正指定宽度和高度,measuredWidth和measuredHeight才真正有值
void measureVertical(int widthMeasureSpec, int heightMeasureSpec) {
//通过for循环去拿我们里面的子布局
for (int i = 0; i < count; ++i) {
final View child = getVirtualChildAt(i);
if (childWeight > 0) {
//记录所有子View的高,方便计算自己的高,这里我们看的是Vertical方向的LinearLayout,所以他只是计算的Height
if (mUseLargestChild && heightMode != MeasureSpec.EXACTLY) {
childHeight = largestChildHeight;
} else if (lp.height == 0 && (!mAllowInconsistentMeasurement
|| heightMode == MeasureSpec.EXACTLY)) {
childHeight = share;
} else {
childHeight = child.getMeasuredHeight() + share;
}
final int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
Math.max(0, childHeight), MeasureSpec.EXACTLY);
final int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin,
lp.width);
//去测量子View
child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
// Child may now not fit in vertical dimension.
childState = combineMeasuredStates(childState, child.getMeasuredState()
& (MEASURED_STATE_MASK>>MEASURED_HEIGHT_STATE_SHIFT));
}
measureChildBeforeLayout(child, i, widthMeasureSpec, 0,
heightMeasureSpec, usedHeight);
}
//测量完之后,接着调用这个方法,我们的布局才有了真正的宽和高,这里进去是给measuredWidth和measuredHeight赋值
setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
heightSizeAndState);
}
总结:
测量都是从外往里递归,他先会把ViewRootImpl的测量模式传到DecorView,然后DecorView再把测量模式传到我们的根布局,依次向底部传,然后,最底层的View会拿子View的宽高来计算自己的宽高,依次向外传
image-20201013215655174.png2. 绘制流程第二步performLayout
private void performLayout(WindowManager.LayoutParams lp, int desiredWindowWidth,
int desiredWindowHeight) {
final View host = mView;
try {
host.layout(0, 0, host.getMeasuredWidth(), host.getMeasuredHeight());
}
}
public void layout(int l, int t, int r, int b) {
if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
onLayout(changed, l, t, r, b);
}
}
走到这里,基本的步骤流程差不多定好了,我们去看具体的View中是怎么实现的,还是用LinearLayout举例
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);
}
}
void layoutVertical(int left, int top, int right, int bottom) {
final int paddingLeft = mPaddingLeft;
int childTop;
int childLeft;
// Where right end of child should go
//计算父窗口推荐的子View宽度
final int width = right - left;
//计算父窗口推荐的子View右侧位置
int childRight = width - mPaddingRight;
// Space available for child
//child可使用空间大小
int childSpace = width - paddingLeft - mPaddingRight;
//通过ViewGroup的getChildCount方法获取ViewGroup的子View个数
final int count = getVirtualChildCount();
//获取Gravity属性设置
final int majorGravity = mGravity & Gravity.VERTICAL_GRAVITY_MASK;
final int minorGravity = mGravity & Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK;
//依据majorGravity计算childTop的位置值
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中其子视图显示的宽和高由measure过程来决定的,因此measure过程的意义就是为layout过程提供视图显示范围的参考值
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
//获取子View的LayoutParams
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);
//依据不同的absoluteGravity计算childLeft位置
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;
}
childTop += lp.topMargin;
//通过垂直排列计算调运child的layout设置child的位置
setChildFrame(child, childLeft, childTop + getLocationOffset(child),
childWidth, childHeight);
childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);
i += getChildrenSkipCount(child, i);
}
}
}
总结:
layout也是从顶层父View向子View的递归调用view.layout方法的过程,即父View根据第一步performMeasure,来获取子View所的布局大小和布局参数,将子View放在合适的位置上,==不过这个方法没有再往外走,只是不断的往里面走==。
3.绘制流程第三步performDraw
performDraw和上面的流程类似
private void performDraw() {
try {
draw(fullRedrawNeeded);
} finally {
mIsDrawing = false;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
private void draw(boolean fullRedrawNeeded) {
Surface surface = mSurface;
if (!surface.isValid()) {
return;
}
if (!drawSoftware(surface, mAttachInfo, xOffset, yOffset, scalingRequired, dirty)) {
return;
}
}
private boolean drawSoftware(Surface surface, AttachInfo attachInfo, int xoff, int yoff,
boolean scalingRequired, Rect dirty) {
// Draw with software renderer.
final Canvas canvas;
final int left = dirty.left;
final int top = dirty.top;
final int right = dirty.right;
final int bottom = dirty.bottom;
canvas = mSurface.lockCanvas(dirty);
// ... ...
mView.draw(canvas);
}
View的绘制流程其实就三个步骤:onMeasure(测量) -> onLayout(摆放) -> onDraw(绘制)
网友评论