Dan*_*mes 2 android android-fragments
我有一个 MainActivity 和 4 个片段。
其中之一称为 ReportFragment,当用户到达最后一个片段 (FinalFragment) 时,它会返回到由fragmentManager 设置为活动状态的 ReportFragment。
java.lang.IllegalStateException: Fragment already added and state has been saved不过,当我将应用程序置于后台并返回到 ReportFragment 时,它会抛出一个异常。
当我为现有片段(ReportFragment)设置参数时会发生这种情况。
Bundle arguments = newFragment.getArguments();
if (arguments == null) {
arguments = new Bundle();
}
arguments.putInt("CONTAINER", containerId);
newFragment.setArguments(arguments);
Run Code Online (Sandbox Code Playgroud)
为什么当应用程序位于前台时不会发生这种情况?
您不能setArguments()对 Fragment 调用两次,如 java 文档中所写:
/**
* 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;
}
Run Code Online (Sandbox Code Playgroud)
相反,您可以执行以下操作来防止异常:
if (newFragment.getArguments() == null) {
Bundle arguments = new Bundle();
arguments.putInt("CONTAINER", containerId);
} else {
newFragment.getArguments().putInt("CONTAINER", containerId);
}
Run Code Online (Sandbox Code Playgroud)
为了告诉您为什么当您的应用程序进入后台时会发生这种情况,重要的是要知道何时调用此代码和平。我假设您在静态 newInstance 方法中调用它,在该方法中引用 Fragment ( ) 的静态引用newFragment。
| 归档时间: |
|
| 查看次数: |
2761 次 |
| 最近记录: |