4 Persisting UI State
Destroying and re-creating activities on rotation can cause headaches, such as GeoQuiz’s bug of reverting to the first question when the device is rotated. To fix this bug, the post-rotation MainActivity instance needs to retain the old value of currentIndex. You need a way to save this data across a runtime configuration change, like rotation.
Luckily, there is a class that survives rotation that you can use to store your state. In this chapter, you will fix GeoQuiz’s UI state loss on rotation bug by storing its UI data in a ViewModel.
A ViewModel is the perfect complement to an Activity because of its simple lifecycle and ability to persist data across configuration changes. It is usually scoped to a ...
Get Android Programming: The Big Nerd Ranch Guide, 5th Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.