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

醉酒当歌 提交于 2020-11-29 19:26:06

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/56795819/android-fragment-is-being-put-on-top-of-the-previous-one-when-coming-back-from-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!