網站首頁 編程語言 正文
前言
有一個經典的問題,我們在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的生命周期,關于Activity的啟動流程,后面單獨寫一篇,本文會帶一部分。
另外布局都是通過setContentView(int)
方法設置的,所以弄清楚setContentView
的流程也很重要,后面也補一篇。
首先要知道Activity的生命周期都在ActivityThread
中, 當我們調用startActivity
時,最終會走到ActivityThread
中的performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { …… Activity activity = null; try { java.lang.ClassLoader cl = appContext.getClassLoader(); // 【關鍵點1】通過反射加載一個Activity activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); …… } catch (Exception e) { …… } try { …… if (activity != null) { …… // 【關鍵點2】調用attach方法,內部會初始化Window相關信息 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()) { // 【關鍵點3】調用Activity的onCreate方法 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } …… } …… return activity; }
performLaunchActivity
中主要是創建了Activity對象,并且調用了onCreate
方法。
onCreate流程中的setContentView
只是解析了xml,初始化了DecorView
,創建了各個控件的對象;即將xml中的 轉化為一個TextView
對象。并沒有啟動View的繪制流程。
上面走完了onCreate,接下來看onResume生命周期,同樣是在ActivityThread
中的performResumeActivity
@Override public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward, String reason) { …… // 【關鍵點1】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; // 【關鍵點2】在這里,開始做View的add操作 wm.addView(decor, l); } else { …… a.onWindowAttributesChanged(l); } } } else if (!willBeVisible) { …… } …… }
handleResumeActivity
中兩個關鍵點
- 調用
performResumeActivity
, 該方法中r.activity.performResume(r.startsNotResumed, reason);
會調用Activity的onResume
方法。 - 執行完Activity的
onResume
后調用了wm.addView(decor, l);
,到這里,開始將此前創建的DecorView添加到視圖中,也就是在這之后才開始布局的繪制流程
到這里,我們應該就能理解,為何onCreate和onResume中無法獲取View的寬高了,一句話就是:View的繪制要晚于onResume。
問題2、為什么View.post為什么可以獲取View寬高?
那接下來我們開始看第二個問題,先看看View.post
的實現。
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
成員變量是否為空,如果不為空,則直接加入到對應的Handler消息隊列中。否則走getRunQueue().post(action);
從Attach字面意思來理解,其實就可以知道,當View執行attach時,才會拿到mAttachInfo
, 因此我們在onResume或者onCreate中調用view.post()
,其實走的是getRunQueue().post(action)
。
接下來我們看一下mAttachInfo
在什么時機才會賦值。
在View.java
中
void dispatchAttachedToWindow(AttachInfo info, int visibility) { mAttachInfo = info; }
dispatch相信大家都不會陌生,分發;那么一定是從根布局上開始分發的,我們可以全局搜索,可以看到
不要問為什么一定是這個,因為我看過,哈哈哈
其實ViewRootImpl
就是一個布局管理器,這里面有很多內容,可以多看看。
在ViewRootImpl
中直接定位到performTraversals
方法中;這個方法一定要了解,而且特別長,下面我抽取幾個關鍵點。
private void performTraversals() { …… // 【關鍵點1】分發mAttachInfo host.dispatchAttachedToWindow(mAttachInfo, 0); …… //【關鍵點2】開始測量 performMeasure(childWidthMeasureSpec, childHeightMeasureSpec); …… //【關鍵點3】開始布局 performLayout(lp, mWidth, mHeight); …… // 【關鍵點4】開始繪制 performDraw(); …… }
再強調一遍,這個方法很長,內部很多信息,但其實總結來看,就是View的繪制流程,上面的【關鍵點2、3、4】。也就是這個方法執行完成之后,我們就能拿到View的寬高了;到這里,我們終于看到和View的寬高相關的東西了。
但還沒結束,我們post出去的任務,什么時候執行呢,上面host可以看成是根布局,一個ViewGroup,通過一層一層的分發,最后我們看看View的dispatchAttachedToWindow
方法。
void dispatchAttachedToWindow(AttachInfo info, int visibility) { mAttachInfo = info; …… // Transfer all pending runnables. if (mRunQueue != null) { mRunQueue.executeActions(info.mHandler); mRunQueue = null; } }
這里可以看到調用了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,轉移到mAttachInfo中的Handler, 等待接下來的調用執行。
這里要結合Handler的消息機制,我們post到Handler中的消息,并不是立刻執行,不要認為我們是先dispatchAttachedToWindow
的,后執行的測量和繪制,就沒辦法拿到寬高。實則不是,我們只是將Runnable放到了handler的消息隊列,然后繼續執行后面的內容,也就是繪制流程,結束后,下一個主線程任務才會去取Handler中的消息,并執行。
結論
- onCreate和onResume中無法獲取View的寬高,是因為還沒執行View的繪制流程。
- view.post之所以能夠拿到寬高,是因為在繪制之前,會將獲取寬高的任務放到Handler的消息隊列,等到View的繪制結束之后,便會執行。
原文鏈接:https://juejin.cn/post/7202231477253095479
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2022-03-16 淺析ORB、SURF、SIFT特征點提取方法以及ICP匹配方法_C 語言
- 2022-11-16 Docker如何安全地停止和刪除容器_docker
- 2022-12-03 FFmpeg?Principle分析Out?put?File?數據結構_Android
- 2022-10-29 python的strip、lstrip、rstrip函數的用法和實例
- 2023-11-15 Linux系統SSH客戶端斷開后保持進程繼續運行配置方法;Python等腳本在終端后臺運行的方法
- 2022-03-12 在CentOS7中安裝和配置ssh_Linux
- 2022-09-26 go使用makefile腳本編譯應用的方法小結_Golang
- 2023-09-18 子組件向父組件傳值的4種方法
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支