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?
Using the Up navigation to return to the parent activity recreates the parent activity. When the parent activity is recreated you lose your selected tab. Rather than saving the selected tab, it is easier to just not recreate the parent activity. This can be done by adding the following line to the parent activity section of your
AndroidManifest
file.This will prevent the parent from being recreated and thus your previously selected tab will still be in the same state.
For example, if the
MainActivity
is the parent with the tabs, then the manifest would look something like this:See also:
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:
When you call the
SecondActivity
, usestartActivityForResult()
to keepMainActivity
informed of theSecondActivity
's lifecycle. When "back" is pressed, capture this event inMainActivity.onActivityResult()
and switch to the second tab:MainActivity: where you currently start your activity:
MainActivity: onActivityResult():
If this behaviour has to be connected to the Action Bar's "Up" button instead of the back button, you have to override
getSupportParentActivityIntent()
orgetParentActivityIntent()
depending on whether you are using the support library or not.SecondActivity: get[Support]ParentActivityIntent():
And then, you can handle this in
MainActivity.onCreate()
.MainActivity: onCreate():
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".