Fragments & the Single-Activity Pattern
What is a Fragment?
A Fragment is a reusable piece of a screen with its own layout and lifecycle, hosted inside an Activity. Think of an Activity as a frame, and Fragments as the swappable pictures inside it. Modern Android apps usually have one Activity and many Fragments, swapped by the Navigation Component.
Why fragments exist
- Reuse — the same fragment can appear on a phone and inside a tablet’s split view.
- Modularity — each screen is a small, focused class.
- Navigation — moving between fragments is lighter than launching new activities.
A basic fragment
class HomeFragment : Fragment(R.layout.fragment_home) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentHomeBinding.bind(view)
binding.title.text = "Home"
binding.button.setOnClickListener {
findNavController().navigate(R.id.action_home_to_detail)
}
}
}
The fragment lifecycle (and a key gotcha)
Fragments have their own lifecycle, similar to activities, but with an extra layer: the fragment’s view can be destroyed while the fragment object lives on. The important callbacks are onCreateView() (build the view), onViewCreated() (set up the view — do your work here), and onDestroyView() (clean up view references).
Gotcha: never keep a binding object pastonDestroyView()— it causes memory leaks. Set it tonullthere if you stored it.
The single-activity pattern
Instead of one Activity per screen, you keep one MainActivity that hosts a NavHostFragment, and every screen is a fragment inside it. This is the approach Google recommends today and pairs perfectly with the Navigation Component (covered in a later lesson).
Passing data between fragments
Use Safe Args (type-safe arguments generated from your navigation graph) rather than raw bundles, or share a ViewModel scoped to the activity so two fragments can read the same data.
// shared ViewModel approach
private val sharedVm: SharedViewModel by activityViewModels()
Common mistakes
- Doing setup in
onCreateView()instead ofonViewCreated(). - Holding the view binding after the view is destroyed (leak).
- Using fragment constructors with arguments — pass data via the navigation graph instead.
Summary: Fragments are reusable screen pieces with their own view lifecycle. One Activity + many Fragments + Navigation Component is the modern standard.