Android - onDestroy() 之后 UI 元素失去范围

发布于 2025-01-07 14:44:33 字数 385 浏览 0 评论 0原文

我正在尝试处理当手机插入某些类型的充电器并进入“汽车模式”或“驾驶模式”时应用程序中出现的问题。

在正在运行的应用程序中,调用onDestroy(),然后立即调用onCreate(),应用程序再次正常启动。但是,后续调用更新 UI 元素(在新创建的主 Activity 中)现在没有任何效果,而且看起来我已经失去了布局的范围。

    RelativeLayout splash = (RelativeLayout) findViewById(R.id.splash);
    splash.setVisibility(View.VISIBLE);

onDestroy() 可能发生什么我没有考虑到的情况?我没有对Destroy 进行太多清理,因为我认为不需要这样做。

I am trying to handle problems that occur in my application when the phone is plugged into certain types of chargers and put into "Car Mode" or "Driving Mode".

In the running application, onDestroy() is called and immediately followed by onCreate(), and the application starts again normally. However, subsequent calls to update UI elements (in the newly created main Activity) now have no effect, and it looks like I've lost scope on my layout.

    RelativeLayout splash = (RelativeLayout) findViewById(R.id.splash);
    splash.setVisibility(View.VISIBLE);

What could be ocurring onDestroy() that I'm not accounting for? I don't do much cleanup onDestroy because I didn't think I needed to.

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

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

发布评论

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

评论(2

对你再特殊 2025-01-14 14:44:33

当调用 onDestroy() 时,Activity 已与 UI 分离,因此对其进行 UI 调用没有任何意义。如果您需要显示启动画面,请在 onCreate()onResume() 中将其设置为 View.VISIBLE,或者也许 onPause()。我不完全确定 onPause() 的行为是否会有所不同。

The Activity has been detached from the UI by the time onDestroy() is called so having UI calls to it doesn't make any sense. If you need the splash to be shown, set it to View.VISIBLE in onCreate(), onResume(), or maybe onPause(). I'm not entirely sure if onPause() would act any different.

表情可笑 2025-01-14 14:44:33

当手机旋转时,活动将被销毁并重新创建。插入车载充电器通常会强制手机进入横向模式,从而将其旋转(很可能是纵向)并调用 onDestroy。有一种方法可以通过一些活动标志来防止这种行为——但谷歌建议不要这样做。

我们需要查看此 Activity 的更多代码才能弄清楚发生了什么。

另外,正如 DeeV 指出的那样,当 onDestroy 被调用时,该活动早已消失,因此它可能不是执行您正在执行的任何操作的正确位置 - 但我们需要更多代码来确定。

作为旁注,向上滑动键盘(在具有滑出式键盘的手机上)将产生相同的效果。

When the phone rotates the activity is destroyed and recreated. Plugging into a car charger usually forces the phone to landscape mode, thus rotating it (from portrait, most likely) and calling onDestroy. There is a way to prevent this behavior with some activity flags -- but Google advises against it.

We need to see some more code for this Activity to figure out what's going on.

Also, as DeeV points out, the activity is long gone by the time onDestroy gets called, so it might not be the right place to be doing whatever it is that you're doing -- but we need more code to be sure.

As a sidenote, sliding the keyboard up (on phone's that have slideout keyboards) will produce the same effect.

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