使用兼容库时 setRetainInstance 不适用于 ListFragment
我试图在方向更改时保存 ListFragment 子类,因此我将 setRetainInstance(true) 添加到 onCreate 函数的末尾。我添加了一个 onSaveInstanceState 方法来将其所有数据添加到一个包中,然后将代码添加到 onActivityCreated 中以加载该数据。不幸的是,它不起作用。
当我在 Log.d 的帮助下添加一些调试消息时,我发现不仅 onSaveInstanceState 没有被调用,而且 onCreate 也被调用(文档似乎说当保留实例为 true 时不应该发生)。 onCreate 和 onActivityCreated 都没有与我的数据捆绑在一起(毫不奇怪)。
我猜这可能是兼容性库的问题,尽管我没有 android 3.0+ 设备来测试它。
感谢任何帮助,如果需要,我可以发布一些代码片段,尽管我没有做任何复杂的事情。
更新:当我改变方向(这应该是这样)时, onDestroy 没有被调用,所以看起来 setRetainInstance 的一些功能正在工作
I'm attempting to save a ListFragment subclass across an orientation change so I added setRetainInstance(true) to the end of my onCreate function. I added an onSaveInstanceState method to add all of it's data to a bundle, then added code into onActivityCreated to load that data back. Unfortunately, it wouldn't work.
When I added some debugging messages with the help of Log.d I discovered that not only was onSaveInstanceState not being called, but onCreate was (which the documentation seems to say shouldn't happen when retainInstance is true). Neither onCreate nor onActivityCreated have bundles with my data (unsuprisingly).
I'm guessing this may be a problem with compatibility library, though I don't have an android 3.0+ device to test this.
Any help is appreciated and I can post some code snippets if necessary, though I'm not doing anything complicated.
Update: onDestroy is not being called when I change orientation (which is how it should be), so it seems that some of setRetainInstance is working
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我终于明白我的问题是什么了。这一切都归结为我忘记添加的一行。在我的 FragmentActivity 子类中,我重写了 onSaveInstanceState,但我从未调用过 super.onSaveInstanceState。显然,与我忘记调用其父类的其他方法不同,当我忘记调用 onSaveInstanceState 的父类版本时, onSaveInstanceState 不会抛出运行时错误,而是 setRetainInstance 只是停止工作。我希望这可以减轻我在解决这个问题时所经历的头痛。
I finally figured out what my problem was. It all came down to a single line I'd forgot to add. In my FragmentActivity subclass I'd overrode onSaveInstanceState, but I never called super.onSaveInstanceState. Apparently, unlike other methods whose parents I'd forgotten to call, onSaveInstanceState won't throw a runtime error when I forget to call the parent classes version of it, instead setRetainInstance just stops working. I hope this saves someone the headache I went through trying to solve this.
看来,当您设置
setRetainInstance = true
时,同时调用onSaveInstanceState()
和onActivityCreated()
,然后Bundle
不会被退回。但是,由于
ListFragment
被保留,您可以简单地将其状态存储到一个字段中,并在onActivityCreated()
内处理它。请记住,
Activity
仍将被销毁并重新创建。It seems, when you set
setRetainInstance = true
while bothonSaveInstanceState()
andonActivityCreated()
are called, thenBundle
will not be returned.However, as the as the
ListFragment
is being retained, you can simply store its state into a field, and handle it insideonActivityCreated()
.Bear in mind, the
Activity
will still be destroyed and recreated.