Alan
Alan

Reputation: 9471

Android Bottom Navigation - Maintaining Activity State

I know it's recommended to use Fragments instead of Activities when working with Bottom Navigation. Due to the current design, I want to avoid having to convert all the Activities

The Design: I am using a Bottom Navigation bar like shownenter image description here

Each tab is an Activity. When you tap on any of the tabs, it launches the activity, startActivity(new Intent(getApplication(), TabActivityName.class));. The problem is that when you switch between these tabs, the state of the Activity is lost.

For example:

  1. Click on the Music tab (Shows a list of artists)
  2. Click on an artist in the Music tab to show the Discography fragment.
  3. Switch to the Video tab
  4. Switch back to the Music tab. (I want the Artist's discographyFragment to still be showing, but it is back at the main List of Artists fragment)

Things I've tried:

  1. Changing each of the tab Activities to android:launchMode="singleTask" and android:alwaysRetainTaskState="true" This only preserves data if you are switching to tabs that were started before the current activity.
  2. Changing each of the tab Activities to android:launchMode="singleInstance" and android:alwaysRetainTaskState="true" But this creates an undesired effect of creating multiple application tabs.

Any other ideas on how to maintain the state of the Activity and which Fragment is loaded when switching tabs?

Upvotes: 0

Views: 2178

Answers (2)

otnemem
otnemem

Reputation: 13

My current app has the same kind of design. Bottom menu has different icons that launches activities and each activity has fragments in it.

I solved the problem by using FLAG_ACTIVITY_REORDER_TO_FRONT before launching the bottom menu activities.

    case R.id.ic_house:
                        Intent intent1=new Intent(context, HomeActivity.class);
                        intent1.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        context.startActivity(intent1);
                        break;
    case R.id.ic_more:
                        Intent intent2=new Intent(context, MoreActivity.class);
                        intent2.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                        context.startActivity(intent5);
                        break;

This question is 3 years old but maybe someone else finds this solution helpful.

Upvotes: 0

RestingRobot
RestingRobot

Reputation: 2978

You could use FragmentStatePagerAdapter in the Activities. However, you should update to fragments, they are designed to handle your situation. The migration is not that bad, most of the logic can simply be copied over.

Upvotes: 1

Related Questions