有一个关于 savedInstanceState 包的问题,当 fragment 首次创建然后重新附加到 Activity 时,您在 fragment 的回调中获得。
所以我使用了 setRetainInstance(true),因此 fragment 不应被销毁,而只是在 Activity 被销毁时与 Activity 分离,然后在配置更改时重新创建 Activity 时重新附加回去。
因此,因为使用此 setRetainInstance(true) 这将导致 savedInstanceState 包在 fragment 的回调中始终为空,例如:onActivityCreated()
, onCreate()
等
到目前为止一切顺利,现在我从一些用户那里收到了一些崩溃(数量非常少),这是由于 fragment 上的 savedInstanceState 不为 null 造成的。
因此,onActivityCreated() 回调正在执行如下操作:
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new CustomAdapter(getActivity(), getListView(), data, savedInstanceState);
setListAdapter(adapter);
setupEmptyListView();
getListView().setOnScrollListener(this);
}
CustomAdapter 在某个时候从它的构造函数中调用一个 loadInstanceState()
方法来完成它的工作,代码如下:
@Override
public void loadInstanceState(Bundle savedInstanceState) {
if (savedInstanceState != null) {
//do some stuff which is causing a crash
}
}
现在我的问题是,当我传递的 savedInstanceState 应始终为 null 时,如何进入该 if 语句。
现在是问题:
Android 是否保证在使用时 setRetainInstance(true)
在 fragment 上,传递给回调的 savedInstanceState 包将始终为空?
谢谢大家的回答!
最佳答案
在这种情况下,我没有发现任何关于 savedInstanceState bundle 必须为 null 的提及。 official documentation说:
public void setRetainInstance (boolean retain)
Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change). This can only be used with fragments not in the back stack. If set, the fragment lifecycle will be slightly different when an activity is recreated:
onDestroy() will not be called (but onDetach() still will be, because the fragment is being detached from its current activity).
onCreate(Bundle) will not be called since the fragment is not being re-created.
onAttach(Activity) and onActivityCreated(Bundle) will still be called.
恕我直言,这是主要区别 - 改变了生命周期。
关于Android:将 savedInstanceState 与 fragment 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15545214/