Challenge: Saving State

Figure out how to persist your boxes across orientation changes from within your View. This can be done with the following View functions:

    protected fun onSaveInstanceState(): Parcelable
    protected fun onRestoreInstanceState(state: Parcelable)

These functions work like Activity and Fragment’s onSaveInstanceState(Bundle) and ViewModel’s SavedStateHandle, but with a few key differences. First, they will only be called if your View has an ID. Second, instead of taking in a Bundle, they return and process an object that implements the Parcelable interface.

Since Bundle implements the Parcelable interface, you can still use that here. You could store your boxes’ data by storing them within a Bundle.

You could also try out the Parcelize Kotlin compiler plugin to help you generate code that implements the Parcelable for you. Parcelize is used in Chapter 27; you can flip ahead to see how to incorporate and use it.

Finally, you must also maintain the saved state of BoxDrawingView’s parent, the View class. Save the result of super.onSaveInstanceState() in your new Bundle and send that result to the superclass when calling super.onRestoreInstanceState(Parcelable).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.151.44