Fragments are reusable, lifecycle-aware pieces of UI that live inside an activity, and they are the building block for tabbed screens on Android. Understanding their lifecycle and pairing them with TabLayout and ViewPager2 is the standard way to build swipeable tabs in the View system.
Key takeaways
- Fragments have their own lifecycle nested inside the host activity's lifecycle.
- TabLayout + ViewPager2 gives swipeable, indicator-backed tabs.
- Use the fragment view lifecycle for observers to avoid leaks.
The fragment lifecycle
A fragment goes through its own create, view-create, start, resume, and destroy phases inside the activity. A common bug is observing data with the fragment's lifecycle instead of its view lifecycle, which leaks observers across view recreation — use viewLifecycleOwner for UI observers.
Building tabs
ViewPager2 hosts a fragment per page, and TabLayoutMediator wires a TabLayout to it so tabs and swiping stay in sync. Each tab is just a fragment, which keeps screens modular and testable.
State and navigation
Hoist shared state into a ViewModel scoped to the activity so tabs can share data, and let the Navigation component manage back-stack behavior. This keeps each fragment focused on its own UI.