4

我想使用代码从堆栈中删除一个活动。这是我的情况

  1. 从页面 AI 转到页面 B。
  2. 从页面 B 我必须使用返回按钮返回页面 A。
  3. 在页面 BI 中,有一个按钮可以转到页面 C。
  4. 当我单击页面 B 中的该按钮时,我正在调用
finish(); //to remove PageB from stack

好的,这是问题所在,当我单击返回按钮时,我从页面 C 转到页面 A。因为它在堆栈中。

当我单击页面 B 中的按钮时,我想从堆栈中删除页面 A。

请注意,在调用页面 B 时,我无法在页面 A 中调用 finish(),因为我想返回页面 A。我不想返回的唯一情况是单击页面 B 中的按钮时。

我怎么能在android中做到这一点?谢谢

4

4 回答 4

5

而不是startActivity在启动 B 时调用 A,调用startActivityForResult. 然后,您对 A 的活动,句柄onActivityResult

现在,在 B 中,当您打开 C 时,setResult在调用完成之前调用。这将允许您设置一些数据以传回 A 的onActivityResult方法。传递一个标志来指示 A 应该关闭自己,然后调用finish. 处理 A's 中的那个标志onActivityResult

这样,每个活动都负责关闭自己,并且您不会人为地弄乱后台堆栈。在简单的 A、B、C 情况下使用意图标志可以正常工作,但如果这 3 个屏幕是更大解决方案的一部分(即 A、B 和 C 位于一堆您不想要的活动的深处),则可能会分崩离析乱来)。

于 2011-09-16T12:41:16.070 回答
4

您可以通过启动 Intent 直接跳转到另一个 Activity,而不是完成当前 Activity。

Intent intent = new Intent(this, MyTarget.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
于 2011-09-16T12:28:01.390 回答
0

您可以使用 startActivity() 从 B 再次调用 A。

于 2011-09-16T12:32:27.983 回答
0

当然,此页面上有更好的答案,但作为一种解决方法,您可以使用 SharedPreferences 将消息传递给 Activity A,请求它也完成。

活动一:

public class A extends Activity {

  public static final String CLOSE_A_ON_RESUME = "CLOSE_A_ON_RESUME";

  @Override
  public void onResume(){
    super.onResume();

    //Retrieve the message
    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean IShouldClose=mPrefs.getBoolean(A.CLOSE_A_ON_RESUME,false);

    if (IShouldClose){

       //remove the message (will always close here otherwise)
       mPrefs.edit().remove(A.CLOSE_A_ON_RESUME).commit();

       //Terminate A
       finish();
    }
}

活动 C:

public class C extends Activity {

  /*
   * Stores an application wide private message to request that A closes on resume
   * call this in your button click handler
   */
  private void finishCthenA(){

    //Store the message
    SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
    mPrefs.edit().putBoolean(A.CLOSE_A_ON_RESUME,true).commit();

    //finish C
    finish();
}

请注意,这有点冒险,因为首选项在重新启动后仍然存在,并且它可以阻止 A 启动,例如,如果您的应用程序在 A 恢复之前被终止。要解决此问题,您还应该删除 A.onCreate() 中的消息

于 2011-09-16T12:52:49.533 回答