ViewPager and fragments — what's the right way to store fragment's state?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
ViewPagers and fragments are fundamental components in Android development, offering a flexible way to implement swiping views in applications. However, one of the challenges developers face is managing and preserving fragment states effectively. This article delves into the intricacies of using ViewPager with fragments and best practices for maintaining their state across configuration changes or while navigating.
ViewPager in Android
The ViewPager widget, a part of the Android Support Library, provides a way to flip between pages of data. It is especially useful for designing swipeable interfaces. There are two main types of ViewPager implementations: ViewPager and its successor ViewPager2. Both enable smooth horizontal swiping between pages represented by fragments, but ViewPager2 is more versatile and responsive, leveraging newer architecture components.
Fragments in ViewPager
Fragments are modular building blocks for activities, providing a reusable portion of your UI. When using a ViewPager, different pages are typically represented by fragments. Managing the fragment lifecycle correctly is crucial in this scenario.
State Management for Fragments
Proper state management within fragments ensures that user actions and fragment instances are preserved correctly. The Android lifecycle automatically saves and restores the state of UI components, but explicit mechanisms are sometimes needed for more complex scenarios involving ViewPagers.
Key Mechanisms:
FragmentStateAdapterorFragmentPagerAdapter:- These adapters link the ViewPager with the fragments you want to display.
FragmentStateAdapter(used withViewPager2) is preferable for cases where you want the pager to destroy any inactive fragments, saving memory. FragmentPagerAdapterkeeps all fragments in memory but is mainly used with the olderViewPager.
onSaveInstanceState()andonViewStateRestored():- Override these methods in your fragments to save and restore any state that should persist through configuration changes.
- Architecture Components ViewModel:
- Using ViewModels is a modern approach to preserve the state across fragment recreations due to lifecycle changes.
- ViewModels retain data even across configuration changes, making them ideal for maintaining UI-related data.
- Use
setRetainInstance(true)wisely:- This method allows a fragment to be retained when the activity is recreated. However, it is deprecated in recent APIs and replaced by ViewModel which is more flexible and lifecycle-aware.
Code Example
Here's a basic example of managing fragment state:
Table Summary
Here is a summary table highlighting key points for managing fragment state with ViewPager:
| Aspect | ViewPager | ViewPager2 | State Management Strategy |
| Adapter | FragmentPagerAdapter | FragmentStateAdapter | Use FragmentStateAdapter for better management |
| Fragment Memory | Retains all in memory | Destroys inactive ones | Use ViewModel to preserve UI state across changes |
| Lifecycle Methods | onSaveInstanceState() | onSaveInstanceState() | Ensure critical data is saved/restored correctly |
| Retention | setRetainInstance(true) | N/A - Use ViewModel | ViewModel provides better lifecycle handling |
Additional Considerations
- Fragment Lifecycle Awareness: Understanding fragment lifecycle stages is vital when using ViewPager. Fragments managed by a ViewPager undergo frequent destruction and recreation based on user navigation or configuration changes.
- Performance Optimization: Minimizing memory usage by relieving the ViewPager of inactive fragments can prevent performance bottlenecks in memory-constrained devices.
- Error Management: Handle fragment transactions and state changes carefully to avoid common pitfalls such as
IllegalStateException.
By leveraging the proper techniques for managing fragments within a ViewPager, developers can ensure an efficient and user-friendly experience within their Android applications. Thorough understanding and implementation of state persistence techniques are crucial in achieving this goal.

