在android中被调用了两次

在android中被调用了两次

本文介绍了片段上的onstart()在android中被调用了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个活动,其中有一个片段.在片段的onStart()中,我有所有网络调用.当app来自后台时,onStart()被调用两次,所有网络都被调用了两次,我还观察到onCreate()仅被调用了一次,有些人遇到了这样的问题.请帮帮我.我的片段交易代码如下

I have an activity on which I have one fragment. In onStart() of fragment I have all network calls.When app comes from background onStart() is getting called twice and all network are called twice and I also observed that onCreate()is called only once.Has some one faced such issue.Please help me out.My code for fragment transaction is as below

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

提前感谢!!!

推荐答案

尝试在替换之前检查片段是否已添加

Try checking whether the fragment is already added before replacing

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

这篇关于片段上的onstart()在android中被调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 17:11