user9132502
user9132502

Reputation: 387

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

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:

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

Now unfortunately when I come back to my app from the background, these 3 fragments get placed on top of the old ones and this creates a bizarre behavior which glitches the UI

This is how I show my fragment when I click on a BottomNavigationView's item:

fragmentManager.beginTransaction().hide(mCurrentFragment).show(mUpcomingViewPagerFragment).commit();
mCurrentFragment = mUpcomingViewPagerFragment; 

How can I fix this behavior?

Upvotes: 0

Views: 46

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 199805

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

Upvotes: 3

Related Questions