Last active
May 15, 2020 18:46
-
-
Save akexorcist/7ecd1a89bfb9ffb1041ecf9eacff5637 to your computer and use it in GitHub Desktop.
Using BaseSavedState to handling state change in base class of inherited custom view
This file contains 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
abstract class BasePostView : FrameLayout { | |
private var title: String? = null | |
private var description: String? = null | |
... | |
override fun onSaveInstanceState(): Parcelable? { | |
val superState: Parcelable? = super.onSaveInstanceState() | |
superState?.let { | |
val state = SavedState(superState) | |
state.title = this.title | |
state.description = this.description | |
return state | |
} ?: run { | |
return superState | |
} | |
} | |
override fun onRestoreInstanceState(state: Parcelable?) { | |
when (state) { | |
is SavedState -> { | |
super.onRestoreInstanceState(state.superState) | |
this.title = state.title | |
this.description = state.description | |
// Update view's state here | |
} | |
else -> { | |
super.onRestoreInstanceState(state) | |
} | |
} | |
} | |
internal class SavedState : BaseSavedState { | |
var title: String? = null | |
var description: String? = null | |
constructor(superState: Parcelable) : super(superState) | |
constructor(source: Parcel) : super(source) { | |
title = source.readString() | |
description = source.readString() | |
} | |
override fun writeToParcel(out: Parcel, flags: Int) { | |
super.writeToParcel(out, flags) | |
out.writeString(title) | |
out.writeString(description) | |
} | |
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