Coder Coder - 9 months ago 42
Android Question

Return to previous tab when activity is destroyed

I have 2 activities

  1. MainActivity

  2. ProjectActivity

MainActivity has 3 tabs (fragments)

  1. Frag1

  2. Frag2

  3. Frag3

When I go to Frag2 and click 'Add' button from action bar, ProjectActivity is started. In Project Activity when I click on 'Cancel' button I am starting MainActivity again. But now when MainActivity is started it shows Frag1.

How can change my code to show Frag2, as user was on Frag2 previously?

I use this simple code to start the MainActivity when cancel button is clicked.

intent = new Intent(this, MainActivity.class);

Answer Source

Do not restart the main activity. Use finish() instead. That takes you back to the original MainActivity instead of creating a new one. This is the same behavior you get from the back button.

See Tasks and Back Stack for a more in-depth view of the back stack.