I’ve successfully implemented onRetainNonConfigurationInstance() for my main Activity to save and restore certain critical components across screen orientation changes.
But it seems, my custom views are being re-created from scratch when the orientation changes. This makes sense, although in my case it’s inconvenient because the custom view in question is an X/Y plot and the plotted points are stored in the custom view.
Is there a crafty way to implement something similar to onRetainNonConfigurationInstance() for a custom view, or do I need to just implement methods in the custom view which allow me to get and set its “state”?
You do this by implementing
View#onSaveInstanceStateandView#onRestoreInstanceStateand extending theView.BaseSavedStateclass.The work is split between the View and the View’s SavedState class. You should do all the work of reading and writing to and from the
Parcelin theSavedStateclass. Then your View class can do the work of extracting the state members and doing the work necessary to get the class back to a valid state.Notes:
View#onSavedInstanceStateandView#onRestoreInstanceStateare called automatically for you ifView#getIdreturns a value >= 0. This happens when you give it an id in xml or callsetIdmanually. Otherwise you have to callView#onSaveInstanceStateand write the Parcelable returned to the parcel you get inActivity#onSaveInstanceStateto save the state and subsequently read it and pass it toView#onRestoreInstanceStatefromActivity#onRestoreInstanceState.Another simple example of this is the
CompoundButton