Android应用程序生命周期和后退按钮

编程入门 行业动态 更新时间:2024-10-28 06:26:02
本文介绍了Android应用程序生命周期和后退按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我读过关于活动的生命周期Android的文档。不过,我很好奇,在应用程序中是如何不同的活动行为。

I've read the Android Docs on the lifecycle of an activity. However, I am curious as to how different activities within an application behaves.

从一些测试,我已经做了,通过一个意图在同一应用程序内活动A过渡到活动B通过的onPause暂停活动A()并创建活动B通过的onCreate()。

From some tests that I've done, transitioning from Activity A to Activity B within the same application via an intent pauses Activity A via onPause() and creates Activity B via onCreate().

奇怪的部分是,当活动B转换回活动A。

The strange part is when Activity B transitions back to Activity A.

如果硬件返回键是pressed,的onPause()被解雇活动B和 onResume()的活动A.被触发这是我所期望的那样。

If the hardware back key is pressed, onPause() is fired for Activity B and onResume() is fired for Activity A. This is what I would expect.

但是,如果在动作条是pressed后退按钮,的onDestroy()被解雇活动A,然后按的onCreate()和 onResume()。

However, if the back button on the ActionBar is pressed, onDestroy() is fired for Activity A followed by onCreate() and onResume().

为什么会这样?

推荐答案

在动作条被称为向上按钮中的返回按钮。这是向上按钮的预期行为,如果你看一下在code它执行的向上的实施,可以看到活动A被重建。

The "back button" on the ActionBar is called the "Up Button". This is the expected behaviour of the Up Button, if you take a look of the implementation of the code which performs the "up", you see that Activity A is recreated.

Intent parentActivityIntent = new Intent(getApplicationContext(), MainActivity.class); parentActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(parentActivityIntent); finish();

您可以定义什么是向上按钮应该做的,不过,我建议坚持默认行为

You can define what the "Up" button should do, however, I suggest to stick to the default behaviour.

@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: // Your Code Here. break; } }

为什么?

的最多的按钮(与此相反的后退按钮)应导航一个级别更高的应用层次,始终。后退按钮应该去的回的,即使它会离开当前应用程序。 你不能只是呼吁结束对当前活动,因为父活动可能已经被垃圾回收和Don' ŧ存在了。

The Up Button (in contrast to the back button) should navigate one level higher in the application hierarchy, always. The back button should go back, even if it will leave the current application. You can't just call finish on the current Activity, because the parent Activity could already be garbage collected and don't exist anymore.

我大量建议阅读官方 Android设计准则,尤其是部分了解高达VS返回。

I heavily suggest to read the official Android Design Guidelines, especially the part about Up vs Back.

更多推荐

Android应用程序生命周期和后退按钮

本文发布于:2023-11-17 04:18:34,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608802.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:生命周期   应用程序   按钮   Android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!