管理Android的后退栈

4

我有一个活动层次结构,我有一个按钮可以让我从活动D转到活动B。

image

问题在于从 D 前往 B 会使得 C 保留在后退栈中,所以如果我执行 A->C->D->B,然后按下返回按钮,它会将我发送到 C 而不是 A(这不是我想要的结果)。
是否有一种方法可以在从 B 点击按钮时删除 C,或者是否有某种解决方法?

你可以使用Fragment来实现,FragmentManager可以帮助你管理堆栈。同时,也可以查看父Activity:http://developer.android.com/training/implementing-navigation/temporal.html - Steve M
2个回答

1
考虑使用A作为调度器。当您想从D启动B并在过程中完成C时,请在D中执行此操作:
// Launch A (our dispatcher)
Intent intent = new Intent(this, A.class);
// Setting CLEAR_TOP ensures that all other activities on top of A will be finished
//  and setting SINGLE_TOP ensures that a new instance of A will not
//  be created (the existing instance will be reused and onNewIntent() will be called)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|Intent.FLAG_ACTIVITY_SINGLE_TOP);
// Add an extra telling A that it should launch B
intent.putExtra("startB", true);
startActivity(intent);

A.onNewIntent()中执行以下操作:
@Override
protected void onNewIntent(Intent intent) {
    if (intent.hasExtra("startB")) {
        // Need to start B from here
        startActivity(new Intent(this, B.class));
    }
}

谢谢,运行得很好。这个方法的效率如何?它是否在运行意图之前一直运行活动A直到onResume()? - Gabriel Gedler
1
可能吧。我不确定在这种情况下是否调用onResume(),因为另一个Activity将被启动。但是也有可能会调用。你可以添加一些日志来自己查看。不过我认为这不是需要担心的效率问题。 - David Wasser

0

我不知道你是如何调用B、C和D的,或者传递了哪些数据,但如果你想要的话,在调用D时可以关闭C。

在C中启动D时,你可以这样做:

Intent intent = new Intent(this, D.class);
startActivity(intent);
finish();

完成后会启动D并关闭C。

如果没有更多信息,这只是一次无法确定的尝试。


A、B和C可以通过按钮栏从任何其他活动中调用,而D只能从C中调用。 我不想在打开D时结束C,因为按返回按钮会使我回到A。 - Gabriel Gedler
这种方法行不通。如果你想从D到B,那么你可能需要使用带有片段管理器的片段,或者创建自己的堆栈管理器。 - TooManyEduardos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接