片段上的onstart()在android中被调用两次

时间:2014-03-14 12:29:00

标签: android android-fragments

我有一个活动,我有一个片段。在片段的onStart()中,我有所有网络调用。当应用程序来自后台onStart()被调用两次并且所有网络被调用两次时我也观察到onCreate()只被调用一次。有人遇到这样的问题。请帮帮我。 我的片段事务代码如下所示

 MainFragment myFragment = new MainFragment ();
                FragmentManager fragmentManager = getSupportFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.content_frame, myFragment, "MyFragment");
                fragmentTransaction.commitAllowingStateLoss();

提前致谢!!!

2 个答案:

答案 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)

commitcommitAllowingStateLoss是异步执行,因此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();
            }
        }