Android源碼解析onResume方法中獲取不到View寬高
前言
有一個經(jīng)典的問題,我們在Activity的onCreate中可以獲取View的寬高嗎?onResume中呢?
對于這類八股問題,只要看過都能很容易得出答案:不能。
緊跟著追問一個,那為什么View.post為什么可以獲取View寬高?
今天來看看這些問題,到底為何?
今日份問題:
- 為什么onCreate和onResume中獲取不到view的寬高?
- 為什么View.post為什么可以獲取View寬高?
基于Android API 29版本。
問題1、為什么onCreate和onResume中獲取不到view的寬高?
首先我們清楚,要拿到View的寬高,那么View的繪制流程(measure—layout—draw)至少要完成measure,【記住這一點】。
還要弄清楚Activity的生命周期,關(guān)于Activity的啟動流程,后面單獨寫一篇,本文會帶一部分。
另外布局都是通過setContentView(int)方法設(shè)置的,所以弄清楚setContentView的流程也很重要,后面也補一篇。
首先要知道Activity的生命周期都在ActivityThread中, 當(dāng)我們調(diào)用startActivity時,最終會走到ActivityThread中的performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
……
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
// 【關(guān)鍵點1】通過反射加載一個Activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
……
} catch (Exception e) {
……
}
try {
……
if (activity != null) {
……
// 【關(guān)鍵點2】調(diào)用attach方法,內(nèi)部會初始化Window相關(guān)信息
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback,
r.assistToken);
……
if (r.isPersistable()) {
// 【關(guān)鍵點3】調(diào)用Activity的onCreate方法
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
……
}
……
return activity;
}
performLaunchActivity中主要是創(chuàng)建了Activity對象,并且調(diào)用了onCreate方法。
onCreate流程中的setContentView只是解析了xml,初始化了DecorView,創(chuàng)建了各個控件的對象;即將xml中的 轉(zhuǎn)化為一個TextView對象。并沒有啟動View的繪制流程。
上面走完了onCreate,接下來看onResume生命周期,同樣是在ActivityThread中的performResumeActivity
@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
……
// 【關(guān)鍵點1】performResumeActivity 中會調(diào)用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); // 設(shè)置不可見
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
……
if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
// 【關(guān)鍵點2】在這里,開始做View的add操作
wm.addView(decor, l);
} else {
……
a.onWindowAttributesChanged(l);
}
}
} else if (!willBeVisible) {
……
}
……
}
handleResumeActivity中兩個關(guān)鍵點
- 調(diào)用
performResumeActivity, 該方法中r.activity.performResume(r.startsNotResumed, reason);會調(diào)用Activity的onResume方法。 - 執(zhí)行完Activity的
onResume后調(diào)用了wm.addView(decor, l);,到這里,開始將此前創(chuàng)建的DecorView添加到視圖中,也就是在這之后才開始布局的繪制流程
到這里,我們應(yīng)該就能理解,為何onCreate和onResume中無法獲取View的寬高了,一句話就是:View的繪制要晚于onResume。
問題2、為什么View.post為什么可以獲取View寬高?
那接下來我們開始看第二個問題,先看看View.post的實現(xiàn)。
public boolean post(Runnable action) {
final AttachInfo attachInfo = mAttachInfo;
// 添加到AttachInfo的Handler消息隊列中
if (attachInfo != null) {
return attachInfo.mHandler.post(action);
}
// 加入到這個View的消息隊列中
getRunQueue().post(action);
return true;
}
post方法中,首先判斷attachInfo成員變量是否為空,如果不為空,則直接加入到對應(yīng)的Handler消息隊列中。否則走getRunQueue().post(action);
從Attach字面意思來理解,其實就可以知道,當(dāng)View執(zhí)行attach時,才會拿到mAttachInfo, 因此我們在onResume或者onCreate中調(diào)用view.post(),其實走的是getRunQueue().post(action)。
接下來我們看一下mAttachInfo在什么時機才會賦值。
在View.java中
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
mAttachInfo = info;
}
dispatch相信大家都不會陌生,分發(fā);那么一定是從根布局上開始分發(fā)的,我們可以全局搜索,可以看到

不要問為什么一定是這個,因為我看過,哈哈哈
其實ViewRootImpl就是一個布局管理器,這里面有很多內(nèi)容,可以多看看。
在ViewRootImpl中直接定位到performTraversals方法中;這個方法一定要了解,而且特別長,下面我抽取幾個關(guān)鍵點。
private void performTraversals() {
……
// 【關(guān)鍵點1】分發(fā)mAttachInfo
host.dispatchAttachedToWindow(mAttachInfo, 0);
……
//【關(guān)鍵點2】開始測量
performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
……
//【關(guān)鍵點3】開始布局
performLayout(lp, mWidth, mHeight);
……
// 【關(guān)鍵點4】開始繪制
performDraw();
……
}
再強調(diào)一遍,這個方法很長,內(nèi)部很多信息,但其實總結(jié)來看,就是View的繪制流程,上面的【關(guān)鍵點2、3、4】。也就是這個方法執(zhí)行完成之后,我們就能拿到View的寬高了;到這里,我們終于看到和View的寬高相關(guān)的東西了。
但還沒結(jié)束,我們post出去的任務(wù),什么時候執(zhí)行呢,上面host可以看成是根布局,一個ViewGroup,通過一層一層的分發(fā),最后我們看看View的dispatchAttachedToWindow方法。
void dispatchAttachedToWindow(AttachInfo info, int visibility) {
mAttachInfo = info;
……
// Transfer all pending runnables.
if (mRunQueue != null) {
mRunQueue.executeActions(info.mHandler);
mRunQueue = null;
}
}
這里可以看到調(diào)用了mRunQueue.executeActions(info.mHandler);
public void executeActions(Handler handler) {
synchronized (this) {
final HandlerAction[] actions = mActions;
for (int i = 0, count = mCount; i < count; i++) {
final HandlerAction handlerAction = actions[i];
handler.postDelayed(handlerAction.action, handlerAction.delay);
}
mActions = null;
mCount = 0;
}
}
這就很簡單了,就是將post中的Runnable,轉(zhuǎn)移到mAttachInfo中的Handler, 等待接下來的調(diào)用執(zhí)行。
這里要結(jié)合Handler的消息機制,我們post到Handler中的消息,并不是立刻執(zhí)行,不要認(rèn)為我們是先dispatchAttachedToWindow的,后執(zhí)行的測量和繪制,就沒辦法拿到寬高。實則不是,我們只是將Runnable放到了handler的消息隊列,然后繼續(xù)執(zhí)行后面的內(nèi)容,也就是繪制流程,結(jié)束后,下一個主線程任務(wù)才會去取Handler中的消息,并執(zhí)行。
結(jié)論
- onCreate和onResume中無法獲取View的寬高,是因為還沒執(zhí)行View的繪制流程。
- view.post之所以能夠拿到寬高,是因為在繪制之前,會將獲取寬高的任務(wù)放到Handler的消息隊列,等到View的繪制結(jié)束之后,便會執(zhí)行。
以上就是Android源碼解析onResume方法中獲取不到View寬高的詳細(xì)內(nèi)容,更多關(guān)于Android onResume獲取不到View寬高的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
android如何設(shè)置Activity背景色為透明色
本篇文章主要介紹了android如何設(shè)置Activity背景色為透明色,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07
Android SurfaceView運行機制剖析--處理切換到后臺再重新進(jìn)入程序時的異常
本文主要介紹Android SurfaceView運行機制,這里整理了詳細(xì)的資料來講解SurfaceView的運行原理,并附示例代碼參考,有需要的小伙伴可以參考下2016-08-08
Android存儲字符串?dāng)?shù)據(jù)到txt文件
這篇文章主要為大家詳細(xì)介紹了Android存儲字符串?dāng)?shù)據(jù)到txt文件,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-10-10
Android BottomNavigationView與Fragment重建與重疊問題解決方法探索
這篇文章主要介紹了Android BottomNavigationView與Fragment重建與重疊問題解決,總的來說這并不是一道難題,那為什么要拿出這道題介紹?拿出這道題真正想要傳達(dá)的是解題的思路,以及不斷優(yōu)化探尋最優(yōu)解的過程。希望通過這道題能給你帶來一種解題優(yōu)化的思路2023-01-01

