从后台返回时,Android片段被置于上一个片段的顶部 [英] Android fragment is being put on top of the previous one when coming back from background

查看:70
本文介绍了从后台返回时,Android片段被置于上一个片段的顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MainActivity中,我有三个片段.还有一个BottomNavigationView处理要显示的片段.

In my MainActivity, I have three fragments. There is also a BottomNavigationView that handles what fragment to show.

这是我在MainActivity的OnCreate中拥有的内容:

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

现在不幸的是,当我从后台回到我的应用程序时,这3个片段被放置在旧片段的顶部,这造成了怪异的行为,使UI出现故障

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

这是我单击BottomNavigationView的项目时显示片段的方式:

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

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

如何解决此问题?

推荐答案

重新创建活动时,片段会自动恢复.因此,您在 onCreate()中所做的任何设置都应使用 if(savedInstanceState == null)检查以确保您不会在已经恢复的.

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

这篇关于从后台返回时,Android片段被置于上一个片段的顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆