How to know when activity is laid out?

浪子不回头ぞ 提交于 2019-12-08 07:37:41

问题


I've got a mapview that I want to put some markers on top of. I'll retrieve these from a webservice when I start the activity, so I need to know the minimum and maximum lat/lng pairs for the current viewport. I'm calling

mMapView.getWidth()
mMapView.getHeight()

But they both return 0 while the activity is starting. I tried putting it in onAttachedToWindow, onResume, onPostCreate, onPostResume, onStart and so on, but to no avail. How can I know that the activity has finished laying out all the views and is ready to give me the correct height and width measurements?


回答1:


I think you have to override onSizeChanged and call getWidth/Height from there. Be aware though that onSizeChanged might get called multiple times during your activity's lifecycle (Everytime the size of the view changes).




回答2:


From this post that I've found googling:

Assuming your view is visible, its size has been assigned by the time the activity's window receives focus. That is, when activity.onWindowFocusChanged is called with hasFocus = true.

The sequence is roughly:

view.onFinishInflate

view.onMeasure

view.onSizeChanged(width, height, 0, 0)

view.onLayout

activity.onWindowFocusChanged(true)

I tried and it worked.

EDIT

I've found that it's probably better using a ViewTreeObserver, see this answer.



来源:https://stackoverflow.com/questions/3386468/how-to-know-when-activity-is-laid-out

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!