Darin Beaudreau
Darin Beaudreau

Reputation: 391

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:

So to simplify, I want it like this.

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?

Upvotes: 2

Views: 1683

Answers (2)

Rod_Algonquin
Rod_Algonquin

Reputation: 26198

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)

Upvotes: 0

ianhanniballake
ianhanniballake

Reputation: 200130

When you move from Activity B to Activity C, call finish() at the same time you call startActivity on Activity C. This will remove Activity B from the task stack.

Upvotes: 6

Related Questions