Fragments
Build modular UIs with Fragments. Learn the fragment lifecycle, ViewBinding in fragments, argument passing, back stack management, and fragment-activity communication.
What Are Fragments?
A Fragment is a reusable UI module that lives inside an Activity. Think of it as a sub-Activity with its own layout, lifecycle, and logic.
Why use Fragments?
- Reuse UI across multiple Activities
- Handle different layouts for phone vs tablet
- Build multi-screen flows without multiple Activities
- Work naturally with Navigation Component
Fragment Lifecycle
Fragments have their own lifecycle that runs alongside the Activity lifecycle. Key callbacks:
onAttach— fragment attached to ActivityonCreate— fragment created (no view yet)onCreateView— inflate the layoutonViewCreated— view ready, set up UI hereonDestroyView— view destroyed (clear view references)onDetach— fragment detached