【问题标题】:Finishing Activity from another activity [duplicate]从另一个活动完成活动[重复]
【发布时间】:2013-03-21 19:11:16
【问题描述】:

假设我有 3 个活动 A、B 和 C。A 通向 B,B 通向 C。我希望能够在 A 和 B 之间来回移动,但是一旦 C 得到,我想完成 A 和 B开始了。我了解如何在通过意图启动 C 时关闭 B,但是如何在 C 启动时关闭 A?

【问题讨论】:

    标签: java android


    【解决方案1】:

    打开 C 活动时使用此标志。

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    

    这将清除 C 之上的所有活动。

    【讨论】:

    • 在我看来,A 和 B 的声音低于 C(即:在 C 之前),而不是高于 C。在这种情况下,FLAG_ACTIVITY_CLEAR_TOP 将无济于事。跨度>
    【解决方案2】:

    由于A 是您的根(开始)活动,请考虑使用A 作为调度程序。当您想启动C 并在它之前(下)完成所有其他活动时,请执行以下操作:

    // Launch ActivityA (our dispatcher)
    Intent intent = new Intent(this, ActivityA.class);
    // Setting CLEAR_TOP ensures that all other activities on top of ActivityA will be finished
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    // Add an extra telling ActivityA that it should launch ActivityC
    intent.putExtra("startActivityC", true);
    startActivity(intent);
    

    ActivityA.onCreate() 中这样做:

    super.onCreate();
    Intent intent = getIntent();
    if (intent.hasExtra("startActivityC")) {
        // Need to start ActivityC from here
        startActivity(new Intent(this, ActivityC.class));
        // Finish this activity so C is the only one in the task
        finish();
        // Return so no further code gets executed in onCreate()
        return;
    }
    

    这里的想法是您使用FLAG_ACTIVITY_CLEAR_TOP 启动 ActivityA(您的调度程序),以便它是任务中的唯一活动,并告诉它您希望它启动什么活动。然后它将启动该活动并自行完成。这将使您在堆栈中只剩下 ActivityC。

    【讨论】:

      猜你喜欢
      • 2013-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-07
      相关资源
      最近更新 更多