Able Alias Able Alias - 9 days ago 4
Android Question

How to go to previous selected tab when pressing an activity action bar back button

I have six Tabs in MainActivity, the second tab have a listview, when user press on the listview item, its open a new Activity with Action bar, so, when user press on the back button of the second activity, I want to go to previous tab (second tab) of Main Activity, but its loading the First Tab (Home Tab).

How I can resolve this problem?

Answer

We have three cases here. The actual back button (regardless it is hardware or software), the Action Bar's parent ("Up") button, and both buttons:

  • Back button case:

When you call the SecondActivity, use startActivityForResult() to keep MainActivity informed of the SecondActivity's lifecycle. When "back" is pressed, capture this event in MainActivity.onActivityResult() and switch to the second tab:

MainActivity: where you currently start your activity:

// Start SecondActivity that way. REQUEST_CODE_SECONDACTIVITY is a code you define to identify your request
startActivityForResult(new Intent(this, SecondActivity.class), REQUEST_CODE_SECONDACTIVITY);

MainActivity: onActivityResult():

// And this is how you handle its result    
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);

    if (requestCode == REQUEST_CODE_SECONDACTIVITY && resultCode == RESULT_CANCEL) {
        switchToTab(2); // switch to tab2 
    }
    // else... other cases
}
  • Action Bar's "Up" button case:

If this behaviour has to be connected to the Action Bar's "Up" button instead of the back button, you have to override getSupportParentActivityIntent() or getParentActivityIntent() depending on whether you are using the support library or not.

SecondActivity: get[Support]ParentActivityIntent():

@Override 
public Intent getSupportParentActivityIntent() { // getParentActivityIntent() if you are not using the Support Library
    final Bundle bundle = new Bundle();
    final Intent intent = new Intent(this, MainActivity.class);

    bundle.putString(SWITCH_TAB, TAB_SECOND); // Both constants are defined in your code
    intent.putExtras(bundle);

    return intent;
} 

And then, you can handle this in MainActivity.onCreate().

MainActivity: onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...

    final Intent intent = getIntent();

    if (intent.hasExtra(SWITCH_TAB)) {
        final int tab = intent.getExtras().getInt(SWITCH_TAB);

        switchToTab(tab); // switch to tab2 in this example
    }

    ...
  • Both buttons case:

Should you wish to handle both buttons the same way (regardless this is a good idea or not, I just don't know), both solutions above can be implemented concurrently with no problem.

Side note: to determine whether this is a good idea or not, this official guide may help. Especially the section "Navigating Up with the App Icon".