Last active
May 15, 2020 18:47
-
-
Save akexorcist/3e339d5c7276c2d9203d85d20499660b to your computer and use it in GitHub Desktop.
Using BaseSavedState to handling state change in derived class of inherited custom view
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class RegularPostView : BasePostView { | |
| private var dividerColorResId: Int = 0 | |
| ... | |
| override fun onSaveInstanceState(): Parcelable? { | |
| val superState: Parcelable? = super.onSaveInstanceState() | |
| superState?.let { | |
| val state = SavedState(superState) | |
| state.dividerColorResId = this.dividerColorResId | |
| return state | |
| } ?: run { | |
| return superState | |
| } | |
| } | |
| override fun onRestoreInstanceState(state: Parcelable?) { | |
| when (state) { | |
| is SavedState -> { | |
| super.onRestoreInstanceState(state.superState) | |
| this.dividerColorResId = state.dividerColorResId | |
| // Update view's state here | |
| } | |
| else -> { | |
| super.onRestoreInstanceState(state) | |
| } | |
| } | |
| } | |
| internal class SavedState : BaseSavedState { | |
| var dividerColorResId: Int = 0 | |
| constructor(superState: Parcelable) : super(superState) | |
| constructor(source: Parcel) : super(source) { | |
| dividerColorResId = source.readInt() | |
| } | |
| override fun writeToParcel(out: Parcel, flags: Int) { | |
| super.writeToParcel(out, flags) | |
| out.writeInt(dividerColorResId) | |
| } | |
| companion object { | |
| @JvmField | |
| val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> { | |
| override fun createFromParcel(source: Parcel): SavedState { | |
| return SavedState(source) | |
| } | |
| override fun newArray(size: Int): Array<SavedState> { | |
| return newArray(size) | |
| } | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment