Here we have three cases. The actual return button (regardless of hardware or software), the parent element of the Action Bar ("Up"), and both buttons:
When you call SecondActivity , use startActivityForResult() to save the MainActivity information about the SecondActivity life cycle. When the back MainActivity.onActivityResult() pressed, write this event to MainActivity.onActivityResult() and switch to the second tab:
MainActivity: where you start your activity now :
// 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 }
- Upper Button Action Panel :
If this behavior should be connected to the Control Panel button instead of the Back button, you must override getSupportParentActivityIntent() or getParentActivityIntent() depending on whether you use the support library or not.
SecondActivity: get [Support] ParentActivityIntent () :
@Override public Intent getSupportParentActivityIntent() {
And then you can handle it 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);
If you want to handle both buttons the same way (whether itβs a good idea or not, I just donβt know), both of the above solutions can be implemented simultaneously without any problems.
Side note: To determine if this is a good idea or not, this official guide can help. Especially the section "Navigation using the application icon."