setRetainInstance not working for ListFragment when using compatibiltiy library

风格不统一 提交于 2019-12-07 05:32:22

问题


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


回答1:


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.




回答2:


It seems, when you set setRetainInstance = true while both onSaveInstanceState() and onActivityCreated() are called, then Bundle 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 inside onActivityCreated().

Bear in mind, the Activity will still be destroyed and recreated.



来源:https://stackoverflow.com/questions/6906531/setretaininstance-not-working-for-listfragment-when-using-compatibiltiy-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!