Last active
December 20, 2018 11:29
-
-
Save 4xes/10b320325af4fe9b6a820aa5ee80b1fa to your computer and use it in GitHub Desktop.
States
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
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 | |
} |
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 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" | |
} | |
} |
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 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