Android java.lang.IllegalStateException:片段已添加,状态已保存
我有一个主要活动和4个片段 其中一个称为ReportFragment,当用户到达最后一个片段(FinalFragment)时,它返回到由fragmentManager设置为活动的ReportFragment 不过,当我将应用程序放在后台并返回到ReportFragment时,它抛出了一个Android java.lang.IllegalStateException:片段已添加,状态已保存,android,android-fragments,Android,Android Fragments,我有一个主要活动和4个片段 其中一个称为ReportFragment,当用户到达最后一个片段(FinalFragment)时,它返回到由fragmentManager设置为活动的ReportFragment 不过,当我将应用程序放在后台并返回到ReportFragment时,它抛出了一个java.lang.IllegalStateException:Fragment已经添加,状态已经保存 Bundle arguments = newFragment.getArguments(); if
java.lang.IllegalStateException:Fragment已经添加,状态已经保存
Bundle arguments = newFragment.getArguments();
if (arguments == null) {
arguments = new Bundle();
}
arguments.putInt("CONTAINER", containerId);
newFragment.setArguments(arguments);
当我为现有片段(ReportFragment)设置参数时,就会发生这种情况
为什么当应用程序位于前台时不会发生这种情况?您不能对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方法中调用它,其中引用片段的静态引用(newFragment
)