java.lang.IollegalStateException:片段已添加,状态已保存



我有一个MainActivity和4个片段。

其中一个被称为ReportFragment,当用户到达最后一个片段(FinalFragment(时,它会返回到由fragmentManager设置为活动的ReportFragment。

不过,当我将应用程序放在后台并返回ReportFragment时,它抛出了一个java.lang.IllegalStateException: Fragment already added and state has been saved

当我为现有的Fragment(ReportFragment(设置参数时,就会发生这种情况。

Bundle arguments = newFragment.getArguments();
if (arguments == null) {
arguments = new Bundle();
}
arguments.putInt("CONTAINER", containerId);
newFragment.setArguments(arguments);

为什么应用程序在前台时不会发生这种情况?

您不能像在Fragment的java文档中所写的那样对其调用setArguments()两次

/**
* Supply the construction arguments for this fragment.  This can only
* be called before the fragment has been attached to its activity; that
* is, you should call it immediately after constructing the fragment.  The
* arguments supplied here will be retained across fragment destroy and
* creation.
*/
public void setArguments(Bundle args) {
if (mIndex >= 0) {
throw new IllegalStateException("Fragment already active");
}
mArguments = args;
}

相反,您可以执行以下操作来防止异常:

if (newFragment.getArguments() == null) {
Bundle arguments = new Bundle();
arguments.putInt("CONTAINER", containerId);
} else {
newFragment.getArguments().putInt("CONTAINER", containerId);
}

为了告诉你为什么当你的应用程序进入后台时会发生这种情况,重要的是要知道你什么时候调用这种代码。我假设您在静态newInstance方法中调用它,在该方法中您引用了Fragment(newFragment(的静态引用。

最新更新