Sobes.tech
Middle

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 in CheckBox).

  • 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. ViewModel survives configuration changes.

  • Saving via SavedStateHandle in ViewModel: Allows automatic saving and restoring of small data volumes in ViewModel, using the same mechanisms as onSaveInstanceState.

// 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.