How is the state of a view saved in Android?
sobes.tech AI
Answer from AI
When the configuration changes (for example, screen rotation), Android destroys and recreates the activity. View state is automatically saved if it has an assigned ID.
Mechanisms for saving view state:
-
Automatic saving: Android remembers certain widget properties with IDs (e.g., text in
TextView, checked state inCheckBox). -
Programmatic Save/Restore: You can manually save and restore state by overriding methods:
// Saving state override fun onSaveInstanceState(): Parcelable? { // Save custom state return super.onSaveInstanceState() }// Restoring state override fun onRestoreInstanceState(savedInstanceState: Parcelable?) { super.onRestoreInstanceState(savedInstanceState) // Restore custom state }
Inside views (classes inheriting from View):
// Saving state in a view
override fun onSaveInstanceState(): Parcelable {
// Save custom state and parent state
return super.onSaveInstanceState()
}
// Restoring state in a view
override fun onRestoreInstanceState(state: Parcelable?) {
// Restore custom state and parent state
super.onRestoreInstanceState(state)
}
-
Saving via
ViewModel: Recommended for saving data not directly related to UI.ViewModelsurvives configuration changes. -
Saving via
SavedStateHandleinViewModel: Allows automatic saving and restoring of small data volumes inViewModel, using the same mechanisms asonSaveInstanceState.
// Example of SavedStateHandle in ViewModel
class MyViewModel(private val state: SavedStateHandle) : ViewModel() {
private val counterKey = "counter"
var counter: Int
get() = state.get(counterKey) ?: 0
set(value) {
state.set(counterKey, value)
}
}
LocalViewStateManager: (Not a standard API, possibly a custom implementation) For more complex state management within a view.
Overall, automatic saving by ID handles basic cases. For saving more complex state and business logic, ViewModel with SavedStateHandle or manual override of save/restore methods are used.