onSaveInstanceState() vs. onRetainCustomNonConfigurationInstance()

杀马特。学长 韩版系。学妹 提交于 2019-12-22 09:59:17

问题


I am using ActionBarSherlock, along with several MenuItems that I dynamically manage, depending on program state. Specifically, I save the MenuItems into instance variables in the Activity's onCreateOptionsMenu() method, and then can show and/or hide them as needed later in the Activity.

However, I found that the MenuItem variables can be lost on configuration changes, such as device rotation. So I also put them into a Parcel and pass them to onSaveInstanceState() for restoral through the savedInstanceState mechanism in the next onCreate() call, if needed.

This seems to work fine in the case of a device rotation. However, if I press the Home button, I get an error:

Unable to marshal value com.actionbarsherlock.internal.view.menu.MenuItemWrapper

Any idea what's the difference, or suggestions how to fix? Thank you!

UPDATE

I found a simple solution using onRetainCustomNonConfigurationInstance(). By overriding this method you can stash an object of a class of your choice when an Activity is being destroyed, and then retrieve it using getLastCustomNonConfigurationInstance(). This seems a lot simpler than messing with Parcelables, etc., and it works in my case.

But I'd still like to know: why do I get the above error using onSaveInstanceState()? And is it generally safe to use onRetainCustomNonConfigurationInstance(), or are there any gotchas?

来源:https://stackoverflow.com/questions/15749106/onsaveinstancestate-vs-onretaincustomnonconfigurationinstance

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