Skip to content

Instantly share code, notes, and snippets.

@akexorcist
Last active May 15, 2020 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akexorcist/7ecd1a89bfb9ffb1041ecf9eacff5637 to your computer and use it in GitHub Desktop.
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
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