// 在 onResume() 回调中获取宽高
Log.e(“measure”,“measure in onResume: width= w i n d o w . d e c o r V i e w . w i d t h , h e i g h t = {window.decorView.width}, height= window.decorView.width,height={window.decorView.height}”)
}
}
大多数人都能直截了当的给出答案:
E/measure: measure in onCreate: width=0, height=0
E/measure: measure in onResume: width=0, height=0
E/measure: measure in View.post: width=1080, height=2340
在 onCreate()
和 onResume()
中是无法获取到宽高的,而 View.post()
回调中可以。从日志打印顺序可以看出来,View.post()
回调中的打印语句是最后执行的。
抛开代码来思考一下这个问题,什么时候可以获取到 View 的宽高? 毫无疑问,最起码肯定得在 View 被测量 这个时间点之后。从上面的结果来看,onCreate()
和 onResume()
发生在这个时间点之前,View.post()
的回调发生在这个时间点之后。我们只要搞清楚这个时间点,问题就迎刃而解了。
View 在什么时间点被测量?
大家都知道 View 的绘制流程发生在 onResume 流程(并不是指 Activity.onResume() 回调)中,但我还是决定从头开始说起,大家权当复习一下。
当冷启动 (应用进程不存在) 一个 app 时,首先要和 zygote 建立 socket 连接,将创建进程需要的参数发送给 zygote, zygote 服务端接收到参数之后调用 ZygoteConnection.processOneCommand()
处理参数,并 fork 出应用进程。最后通过