简体   繁体   中英

Returning to the proper activity when pressing the BACK button?

I'm creating an app with multiple screens the user will have to navigate through. Specifically, I'm currently working on a set of activities that must link together as follows:

  • Main Activity -> a button click leads to "CreateCharacterActivity" -> a button click leads to "CharacterMainActivity"
  • The BACK button on "CharacterMainActivity" should lead back to MainActivity without showing the CreateCharacterActivity again.
  • This behavior should be similar in other areas of the app, except it should restore the state the activity the BACK button leads to was in before it was paused.

So to simplify, I want it like this.

  • Activity A -> Activity B -> Activity C
  • BACK button causes Activity C to return to Activity A without going through Activity B.

I tried doing this:

@Override
public void onBackPressed() {
    super.onBackPressed();
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
    finish();
}

But this just invokes a new instance of MainActivity. When I then press BACK at that MainActivity instance, it takes me back to CharacterMainActivity.

How can I achieve this? I'm assuming it involves accessing the Activity stack?

从活动B移到活动C时,请在活动C上调用startActivity的同时调用finish() 。这将从任务堆栈中删除活动B。

You can start the child activities for result and then finish the child activities with the result also with the same request code.

To start the child activity:

startActivityForResult (Intent intent, int requestCode)

for finish all the child activity

finishActivity (int requestCode)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM