如何知道活动何时安排?

发布于 2024-09-12 02:28:32 字数 284 浏览 1 评论 0原文

我有一个地图视图,我想在其上放置一些标记。当我开始活动时,我将从网络服务中检索这些,因此我需要知道当前视口的最小和最大纬度/经度对。我正在打电话,

mMapView.getWidth()
mMapView.getHeight()

但活动开始时它们都返回 0。我尝试将其放在onAttachedToWindow、onResume、onPostCreate、onPostResume、onStart等中,但无济于事。我如何知道活动已完成所有视图的布局并准备好为我提供正确的高度和宽度测量值?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

小草泠泠 2024-09-19 02:28:32

从我在谷歌搜索中发现的这篇文章

假设你的视图是可见的,它的
大小已被分配的时间
Activity 的窗口获得焦点。那
就是,当activity.onWindowFocusChanged时
使用 hasFocus = true 进行调用。

顺序大致为:

view.onFinishInflate

查看.onMeasure

view.onSizeChanged(宽度,高度,0,0)

view.onLayout

activity.onWindowFocusChanged(true)

我尝试过,它有效。

编辑

我发现使用ViewTreeObserver可能更好,请参阅这个答案

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.

枫林﹌晚霞¤ 2024-09-19 02:28:32

我认为你必须覆盖 onSizeChanged 并从那里调用 getWidth/Height。请注意,onSizeChanged 在您的 Activity 生命周期中可能会被多次调用(每次视图大小发生变化时)。

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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文