Skip to content

Instantly share code, notes, and snippets.

@akexorcist
Last active May 15, 2020 18:44
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/e7c08b8c79afaecaeaa5fa4ad0031595 to your computer and use it in GitHub Desktop.
Save akexorcist/e7c08b8c79afaecaeaa5fa4ad0031595 to your computer and use it in GitHub Desktop.
Using BaseSavedState to handling state changes in single Custom View (Non-inherited Custom View)
class PostView : FrameLayout {
private var title: String? = null
private var description: String? = null
private var dividerColorResId: Int = 0
...
override fun onSaveInstanceState(): Parcelable? {
val superState: Parcelable? = super.onSaveInstanceState()
superState?.let {
val state = SavedState(superState)
state.title = this.title
state.description = this.description
state.dividerColorResId = this.dividerColorResId
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
this.dividerColorResId = state.dividerColorResId
// Restore view's state here
}
else -> {
super.onRestoreInstanceState(state)
}
}
}
internal class SavedState : BaseSavedState {
var title: String? = null
var description: String? = null
var dividerColorResId: Int = 0
constructor(superState: Parcelable) : super(superState)
constructor(source: Parcel) : super(source) {
title = source.readString()
description = source.readString()
dividerColorResId = source.readInt()
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeString(title)
out.writeString(description)
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