IllegalStateException:片段已添加到 tabhost 片段中 [英] IllegalStateException: Fragment already added in the tabhost fragment
问题描述
FATAL EXCEPTION: main
Process: com.example.loan, PID: 24169
java.lang.IllegalStateException: Fragment already added: FormFragment{428f10c8 #1 id=0x7f050055 form}
at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1192)
at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:722)
at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1533)
at android.support.v4.app.FragmentManagerImpl$2.run(FragmentManager.java:489)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1484)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:450)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5068)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:792)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:608)
at dalvik.system.NativeStart.main(Native Method)
所以,我有一个使用 tabhost 构建的 android 应用程序.一共三个tab,tab2里面有一个按钮,tab2里面有一个进行fragment事务的按钮(就是调用fragment活动中的函数)
So, I have an android app that build with the tabhost. There are three tabs in total, in the tab2, there is a button to make the fragment transaction in tab2 (which is calling the function in the fragment activity)
FragmentTransaction t = getSupportFragmentManager().beginTransaction();
t.replace(R.id.realtabcontent, mFrag);
t.addToBackStack(null);
t.commit();
如果我这样运行会有异常:
There is exception if I run like this:
- 在tab2里面,我按下按钮来改变片段
- 转到其他标签(例如标签 1 或标签 3)
- 按返回按钮
- 抛出异常
如何解决这个问题?感谢帮助
How to fix that? Thanks for helping
推荐答案
当我们在关闭之前尝试添加相同的片段或 DialogFragment 两次时会发生这种情况,
This happens when we try to add same fragment or DialogFragment twice before dismissing,
只要打电话
if(mFragment.isAdded())
{
return; //or return false/true, based on where you are calling from
}
话虽如此,我看不出有什么理由删除旧片段并再次添加相同的片段,因为我们可以通过简单地将参数传递给片段内的方法来更新 UI/数据
Having said that, I don't see any reason why to remove old fragment and add the same fragment again since we can update the UI/data by simply passing parameters to the method inside the fragment
这篇关于IllegalStateException:片段已添加到 tabhost 片段中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!