edmond
edmond

Reputation: 843

Remember selected tab in android

I have an activity A containg a tablayout with 2 tabs: tab1 at position 1 and tab2 at position 2.
Either tab contains a recycler view with clickable items. Clicking starts an activity B.
If a select tab1 and click on one of its items, activity B gets started and with the back button I go back to activity A where tab1 is selected. But if I do the same with tab2 the tab1 is still the selected one whenever I go back to activity A.
How can I remember the selected tab so that whenever I leave activity B the previously selected tab is shown and not always tab1?

Upvotes: 2

Views: 1455

Answers (3)

martinseal1987
martinseal1987

Reputation: 2429

Yes this is an old post my apologies for that, but the answers here are dreadful, so the way to do this generally would be to save and restore instance state so create a string that just serves as a key, mine is called CURRENT_FRAGMENT, then in your save instance state

@Override
   public void onSaveInstanceState(@NonNull Bundle outState) {
       super.onSaveInstanceState(outState);
       outState.putInt(CURRENT_FRAGMENT, 
       requestTabLayout.getSelectedTabPosition());
 }

and then for restoring it you can either override on Restore Instance State or you can check the savedInstanceState in onCreate or onStart something like this

if (savedInstanceState  != null){
    requestTabLayout.getTabAt(savedInstanceState.getInt(CURRENT_FRAGMENT))
    .select();
} 

Upvotes: 0

Matias Elorriaga
Matias Elorriaga

Reputation: 9150

Make sure you are implementing up navigation in the proper way:

<application ... >
...
<!-- The main/home activity (it has no parent activity) -->
<activity
    android:name="com.example.myfirstapp.MainActivity" ...>
    ...
</activity>
<!-- A child of the main activity -->
<activity
    android:name="com.example.myfirstapp.DisplayMessageActivity"
    android:label="@string/title_activity_display_message"
    android:parentActivityName="com.example.myfirstapp.MainActivity" >
    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
        android:name="android.support.PARENT_ACTIVITY"
        android:value="com.example.myfirstapp.MainActivity" />
</activity>

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    // Respond to the action bar's Up/Home button
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Source: https://developer.android.com/training/implementing-navigation/ancestral.html

Upvotes: 0

edmond
edmond

Reputation: 843

Setting

android:launchMode=singleTop

for the starting activity solves the problem for me. No need to save any tab position.

Upvotes: 1

Related Questions