Last active
May 15, 2020 18:44
-
-
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)
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
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