In my MainActivity, I have three fragments. There is also a BottomNavigationView that handles what fragment to show.
This is what I have in my MainActivity\'s OnCreate:
Fragments are automatically restored when your activity is recreated. Therefore any setup you do in onCreate()
should be guarded with a if (savedInstanceState == null)
check to ensure that you don't add additional Fragments on top of the ones already restored.
if (savedInstanceState == null) {
// Create new Fragment instances
mTrendingFragment = new TrendingFragment();
mFavoriteFragment = new FavoriteFragment();
mUpcomingViewPagerFragment = new UpcomingViewPagerFragment();
// And add those new instances to the FragmentManager
fragmentManager.beginTransaction().add(R.id.content_main, mTrendingFragment, "3").hide(mTrendingFragment).commit();
fragmentManager.beginTransaction().add(R.id.content_main, mFavoriteFragment, "2").hide(mFavoriteFragment).commit();
fragmentManager.beginTransaction().add(R.id.content_main, mUpcomingViewPagerFragment, "1").commit();
} else {
// Get the already existing fragments from FragmentManager
mTrendingFragment = (TrendingFragment) fragmentManager.findFragmentByTag("3");
mFavoriteFragment = (FavoriteFragment) fragmentManager.findFragmentByTag("2");
mUpcomingViewPagerFragment = (UpcomingViewPagerFragment) fragmentManager.findFragmentByTag("1");