简体   繁体   中英

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 shown在此处输入图片说明

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM