我有以下代码
@Override
public void updateSubFragments() {
Fragment myFragment1 = getFragment1();
Fragment myFragment2 = getFragment2();
if (isTrue) {
getFragmentManager().beginTransaction().hide(myFragment2).show(myFragment1).commitAllowingStateLoss();
} else {
getFragmentManager().beginTransaction().hide(myFragment1).show(myFragment2).commitAllowingStateLoss();
}
}
private MyFragment getFragment1() {
MyFragment myFragment = (MyFragment) getChildFragmentManager()
.findFragmentByTag(MY_FRAGMENT);
if (myFragment == null) {
myFragment = new MyFragment();
getChildFragmentManager().beginTransaction()
.add(R.id.myFragment, myFragment, MY_FRAGMENT).commit();
}
return myFragment;
}
并获得此例外
java.lang.IllegalStateException: Activity has been destroyed
at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1333)
at android.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.app.BackStackRecord.commit(BackStackRecord.java:574)
我认为原因可能是Fragment引用了被破坏的Activity,但是,Fragment刚刚被创建,因为它之前是null。任何想法为什么会发生此异常或如何解决它?