我有一个关于 Android 应用程序中 Activity 的相当简单的问题。我还是个新手。
在我当前的 android 应用程序中,我有大约 10 个 Activity 。如果其中一个 Activity 已经在 Activity 堆栈中很远,我想重新打开它,可以调用:
Intent iLogin = new Intent(this, Login.class);
startActivity(iLogin);
如果还是有点糊涂,我再举个例子。应用程序以 Activity 1 启动。然后用户打开 Activity 2。稍后他打开 Activity 3 以执行操作。执行 Action 后,我想让用户回到activity 1,调用上面的代码可以吗?它是从堆栈中获取 Activity ,还是创建新 Activity ?如果不是,我如何从堆栈中获取 Activity?
更新:我对回收 Activity 很感兴趣,而不是每次都创建新的 Activity 。例如,并非所有 Activity 都需要创建新 Activity 。其中一些只显示数据,可以根据用户请求刷新。
最佳答案
简而言之:不,您的代码 fragment 会将 Login
的新实例推送到 Activity 堆栈中。请在 Tasks and Back Stack 中阅读有关 Activity 堆栈行为的更多信息。 developer.android.com 上的文章。
Because the activities in the back stack are never rearranged, if your application allows users to start a particular activity from more than one activity, a new instance of that activity is created and popped onto the stack (rather than bringing any previous instance of the activity to the top). As such, one activity in your application might be instantiated multiple times (even from different tasks), as shown in figure 3.
图 3:
在Managing Tasks下也给出了一个可能的解决方案.您可以添加 flag到 Intent 指定在堆栈中已存在 Activity 时 Android 应该执行的操作。我会说 FLAG_ACTIVITY_REORDER_TO_FRONT
或 FLAG_ACTIVITY_CLEAR_TOP
可能是您正在寻找的,但一定要浏览其他选项,因为可能有一个更适合您的需求。
或者,如果您的应用中的流程允许,您可以在用户导航离开 Activity 时完成该 Activity 。例如,在您的示例中:如果用户从 Activity #2 导航到 Activity #3,请完成 #2。从 #3 按下后退按钮将导致 Activity #1 被呈现,因为它将成为堆栈顶部的 Activity 。
关于java - Android 中的 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8767078/