为什么onCreate和onResume中获取不到view的宽高?
(基于Android-33代码梳理-打断点倒推都流程)
获取View宽高都时候,一般我们都是是用View.post()
现在抛出问题:
- 为什么在onResume都时候不能获取宽高呢?
为什么在onResume都时候不能获取宽高呢?
- 先看一下宽高是如何获取的
想要拿到View的宽高,那么View的绘制流程(onMeasure—onLayout—onDraw)需要要完成measure,
View.java
public final int getMeasuredHeight() {
return mMeasuredHeight & MEASURED_SIZE_MASK;
}
private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
mMeasuredWidth = measuredWidth;
mMeasuredHeight = measuredHeight;
...
}
protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {
boolean optical = isLayoutModeOptical(this);
if (optical != isLayoutModeOptical(mParent)) {
Insets insets = getOpticalInsets();
int opticalWidth = insets.left + insets.right;
int opticalHeight = insets.top + insets.bottom;
measuredWidth += optical ? opticalWidth : -opticalWidth;
measuredHeight += optical ? opticalHeight : -opticalHeight;
}
setMeasuredDimensionRaw(measuredWidth, measuredHeight);
}
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
- 现在来看
onMeasure
是什么时候完成的,onMeasure
打一个断点可以发现是doTraversal() -> performTraversals()
方法走下来的。
ViewRootImpl.java
final class TraversalRunnable implements Runnable {
@Override
public void run() {
doTraversal();
}
}
final TraversalRunnable mTraversalRunnable = new TraversalRunnable();
void scheduleTraversals() {
if (!mTraversalScheduled) {
...
mChoreographer.postCallback(
Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
...
}
}
- 继续在scheduleTraversals方法加断点,找到堆栈信息
------>scheduleTraversals:2437, ViewRootImpl (android.view)
----->requestLayout:2084, ViewRootImpl (android.view)
---->setView:1314, ViewRootImpl (android.view)
--->addView:411, WindowManagerGlobal (android.view)
-->addView:150, WindowManagerImpl (android.view)
->handleResumeActivity:5048, ActivityThread (android.app)
- 现在来看
handleResumeActivity
方法中都做了什么
@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
……
// performResumeActivity 中会调用activity的onResume方法!!!
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
……
final Activity a = r.activity;
……
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;
……
if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
// 在这里,做了WindowManagerImpl的addView操作!!!
wm.addView(decor, l);
} else {
……
a.onWindowAttributesChanged(l);
}
}
} else if (!willBeVisible) {
……
}
……
}
再结合上面的堆栈信息不难发现,执行完Activity的onResume后调用了
wm.addView(decor, l)之后
才开始布局的绘制流程。
总结:View的绘制要晚于onResume!。