问题
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:
- Click on the Music tab (Shows a list of artists)
- Click on an artist in the Music tab to show the Discography
fragment. - Switch to the Video tab
- Switch back to the Music tab. (I want the Artist's
discographyFragmentto still be showing, but it is back at the main List of Artistsfragment)
Things I've tried:
- Changing each of the tab
Activitiestoandroid:launchMode="singleTask"andandroid:alwaysRetainTaskState="true"This only preserves data if you are switching to tabs that were started before the currentactivity. - Changing each of the tab
Activitiestoandroid:launchMode="singleInstance"andandroid: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?
回答1:
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.
来源:https://stackoverflow.com/questions/44011805/android-bottom-navigation-maintaining-activity-state