Skip to content

Instantly share code, notes, and snippets.

@4xes
Last active December 20, 2018 11:29
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 4xes/10b320325af4fe9b6a820aa5ee80b1fa to your computer and use it in GitHub Desktop.
Save 4xes/10b320325af4fe9b6a820aa5ee80b1fa to your computer and use it in GitHub Desktop.
States
fun Map<String, Parcelable>.toBundle(): Bundle {
val output = Bundle()
for (key in keys) {
output.putParcelable(key, this[key])
}
return output
}
fun <T : Parcelable>Bundle.toMap(c: Class<T>): ArrayMap<String, T> {
val output = ArrayMap<String, T>()
for (key in keySet()) {
output[key] = c.cast(getParcelable(key))
}
return output
}
class StatePreferences @Inject constructor(private val preferences: SharedPreferences) {
fun removeScrollPosition() {
preferences.edit().remove(SCROLL_POSITION).apply()
}
fun restoreScrollPosition(): Int {
return preferences.getInt(SCROLL_POSITION, RecyclerView.NO_POSITION)
}
fun saveScrollPosition(scrollPosition: Int) {
if (scrollPosition == RecyclerView.NO_POSITION) {
preferences.edit().remove(SCROLL_POSITION).apply()
} else {
preferences.edit().putInt(SCROLL_POSITION, scrollPosition).apply()
}
}
companion object {
private const val KEY_ = "state_"
private const val VIDEO_LIST_ ="${KEY_}video_list_"
private const val SCROLL_POSITION = "${VIDEO_LIST_}scroll_position"
}
}
abstract class StatesActivity: BaseActivity() {
var states = ArrayMap<String, Parcelable>()
fun saveState(key: String, state: Parcelable) {
states[key] = state
}
fun restoreState(key: String): Parcelable? = states[key]
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putBundle(KEY_STATES, states.toBundle())
}
override fun onRestoreInstanceState(savedInstanceState: Bundle?) {
super.onRestoreInstanceState(savedInstanceState)
states = savedInstanceState?.getBundle(KEY_STATES)?.toMap(Parcelable::class.java)?: states
}
companion object {
const val KEY_STATES = "states"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment