Fragments
Fragments
As your Android app grows beyond a single screen, you quickly discover that one Activity per screen is too coarse-grained. A tablet needs to show a master list next to a detail panel simultaneously, while a phone shows each in turn. Duplicating the layout logic inside two separate Activities is unmaintainable. Android solved this with the Fragment — a self-contained, reusable piece of UI and behavior that lives inside an Activity but manages its own view and its own lifecycle.
What a Fragment Is
A Fragment is a class in androidx.fragment.app that represents a portion of the user interface or behavior inside an Activity. Think of it as a modular sub-screen: it has its own layout XML, its own Java class, and its own lifecycle that runs nested inside the host Activity's lifecycle. A single Activity can host multiple Fragments, swap them in and out, and even reuse the same Fragment class in several Activities.
Creating a Fragment
A Fragment class overrides onCreateView() to inflate its layout, and optionally onViewCreated() to set up views after inflation. You should not find views or set listeners in the constructor — the view does not exist yet at construction time.
The corresponding layout file res/layout/fragment_profile.xml is an ordinary layout XML with a root element — for example a ConstraintLayout — exactly as you would write for an Activity.
Adding a Fragment to an Activity
Fragments are managed by a FragmentManager. You can either declare a Fragment statically in the Activity's layout XML, or add it dynamically at runtime through a FragmentTransaction. The dynamic approach is almost always what you want because it lets you replace and animate Fragments.
Static declaration (layout XML) — simplest, but not replaceable at runtime:
Dynamic transaction (Java) — the flexible approach:
savedInstanceState == null. When the device rotates, Android recreates the Activity AND automatically restores any Fragments that were already committed to the back-stack. If you unconditionally add the Fragment again, you end up with duplicate Fragment instances layered on top of each other.
The Fragment Lifecycle
The Fragment lifecycle runs alongside the host Activity's lifecycle, but has additional callbacks specific to its relationship with the Activity and its own view:
onAttach(context)— Fragment is attached to the Activity. TheContextis now available.onCreate(savedInstanceState)— Fragment is created. Initialize non-view state here (ViewModels, arguments).onCreateView()— Inflate and return the Fragment's view hierarchy.onViewCreated(view, savedInstanceState)— View is ready. Set up listeners, observe LiveData, populate UI here.onStart()— Fragment becomes visible.onResume()— Fragment is in the foreground and interactive.onPause()— Fragment loses focus (another Fragment or Activity comes to the foreground).onStop()— Fragment is no longer visible.onDestroyView()— The view hierarchy is being destroyed. Release any references to views here to avoid memory leaks.onDestroy()— Fragment itself is destroyed.onDetach()— Fragment is detached from the Activity.
onDestroyView(). ViewBinding makes this easy with the pattern: binding = null; in onDestroyView().
Fragment Arguments — the newInstance Pattern
Never pass data to a Fragment through a constructor with parameters. Android will recreate the Fragment via its no-arg constructor when restoring state, losing any constructor arguments. The correct approach is the newInstance factory pattern: pack data into a Bundle and attach it via setArguments().
At the call site in the Activity:
replace() with addToBackStack() when navigating forward. replace() swaps out the current Fragment; addToBackStack() ensures the system Back button reverses the transaction and restores the previous Fragment, giving users the navigation experience they expect.
When to Use Fragments
- Multi-pane layouts: Show list + detail side-by-side on tablets; one pane at a time on phones.
- Tab navigation: Each tab is a Fragment inside a
ViewPager2or a bottom navigation bar. - Reusable UI sections: A shared toolbar, a map view, or a comments section that appears on multiple screens.
- Jetpack Navigation: The Navigation component manages a single-Activity app where every screen is a Fragment destination — this is the recommended modern architecture.
Summary
A Fragment is a modular, reusable UI component that lives inside an Activity. It has its own lifecycle (onCreateView, onViewCreated, onDestroyView being the most important callbacks for UI work), its own layout, and its own state. Data is passed in via the newInstance argument bundle pattern, not constructor arguments. Fragment transactions — add, replace, addToBackStack — are the mechanism by which an Activity composes and navigates between multiple Fragments. In the next lesson you will use the Jetpack Navigation component, which builds on Fragments to give you a complete screen-navigation graph.