4

I want to remove an activity from stack using code.Heres my case

  1. From page A I am going to page B.
  2. From page B i have to return to page A using return button.
  3. In page B I am having a button which takes to page C.
  4. When I click that button in page B , I am calling
finish(); //to remove PageB from stack

Ok, Here is the issue, From Page C when I click the return button I am taken to page A. because it is in stack.

I want to remove Page A from stack when I click the button in page B.

Please note that I cant call a finish() in page A when calling Page B because I want to return back to page A. Only case I dont want to return is when the button in page B is clicked.

How can I do this in android? Thanks

4

4 に答える 4

5

startActivityB を開始するときに A を呼び出すのではなく、 を呼び出しますstartActivityForResult。次に、A のアクティビティで、 を処理しonActivityResultます。

ここで、B で C を開いたときに、呼び出しsetResultを終了する前に呼び出します。onActivityResultこれにより、一部のデータを設定して A のメソッドに戻すことができます。A が自身を閉じてから を呼び出す必要があることを示すフラグを渡しますfinish。そのフラグを A's で処理しonActivityResultます。

このように、各アクティビティはそれ自体を閉じる責任があり、バックスタックを人為的にいじることはありません。インテント フラグの使用は、単純な A、B、C のケースでは問題なく機能しますが、これら 3 つの画面がより大きなソリューションの一部である場合 (つまり、A、B、C が望ましくないアクティビティのスタックの奥深くにある場合) はおそらく機能しなくなります。手を出す)。

于 2011-09-16T12:41:16.070 に答える
4

現在のアクティビティを終了する代わりに、インテントを開始して別のアクティビティに直接ジャンプできます。

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 を使用してメッセージをアクティビティ A に渡し、アクティビティ A も終了するように要求することができます。

アクティビティ 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 に答える