Android fragment is being put on top of the previous one when coming back from background

前端 未结 1 1677
死守一世寂寞
死守一世寂寞 2021-01-27 19:12

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:

1条回答
  •  醉梦人生
    2021-01-27 20:00

    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");
    

    0 讨论(0)
提交回复
热议问题