我有一个活动,我有一个片段。在片段的onStart()中,我有所有网络调用。当应用程序来自后台onStart()被调用两次并且所有网络被调用两次时我也观察到onCreate()只被调用一次。有人遇到这样的问题。请帮帮我。 我的片段事务代码如下所示
MainFragment myFragment = new MainFragment ();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.content_frame, myFragment, "MyFragment");
fragmentTransaction.commitAllowingStateLoss();
提前致谢!!!
答案 0 :(得分:4)
在替换
之前,请尝试检查片段是否已添加final FragmentManager fragmentManager = getSupportFragmentManager();
final Fragment content = fragmentManager.findFragmentById(R.id.content_frame);
if (content == null || !(content instanceof MainFragment)) {
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
final MainFragment myFragment = new MainFragment();
fragmentTransaction.replace(R.id.content_frame, myFragment, "MyFragment");
fragmentTransaction.commitAllowingStateLoss();
}
答案 1 :(得分:0)
commit
或commitAllowingStateLoss
是异步执行,因此fragmentManager.findFragmentById(R.id.content_frame);
将在第一个null
完成之前commit
,这将导致replace
被称为两次。
您可以调试onStart
函数,并查看当前Fragment
对象的hashCode。
我将commit
替换为commitNow
:
FragmentManager fragmentManager = activity.getFragmentManager();
Fragment lifeFragment = fragmentManager.findFragmentByTag(TAG_FRAGMENT);
if (lifeFragment == null || !(lifeFragment instanceof LifeFragment)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
fragmentManager.beginTransaction()
.add(new LifeFragment(), TAG_FRAGMENT)
.commitNowAllowingStateLoss();
}else {
fragmentManager.beginTransaction()
.add(new LifeFragment(), TAG_FRAGMENT)
.commitAllowingStateLoss();
}
}