问题
I am using ActionBarSherlock, along with several MenuItem
s that I dynamically manage, depending on program state. Specifically, I save the MenuItem
s 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 Parcelable
s, 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