Fragments — Screens Inside Activities
You have built Sprout with Compose. Then you join a team whose version of Sprout was written years ago, and every screen is a fragment. Millions of apps look like this, so you need to read them confidently, even if you rarely start new ones this way.
The rule
A fragment is a screen-part an activity hosts; its view can die while it lives.
A fragment is a reusable portion of UI with its own lifecycle, always hosted by an activity. In View-based apps, one activity often shows many screens by swapping fragments in and out of a container, much as NavHost swaps composables.
class PlantDetailFragment : Fragment(R.layout.fragment_plant_detail) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.findViewById<TextView>(R.id.name).text = "Monstera"
}
}What makes fragments tricky is that they have two lifecycles:
- The fragment itself: attached to the activity, created, started, resumed, and so on, mirroring the activity.
- Its view: built in
onCreateView, torn down inonDestroyView. When a fragment goes onto the back stack its view is destroyed but the fragment object stays, and the view is rebuilt when the user returns. Holding a view reference afteronDestroyViewleaks memory.
Screens change through the FragmentManager:
supportFragmentManager.commit {
replace(R.id.container, PlantDetailFragment())
addToBackStack(null)
}addToBackStack records the change, so Back reverses it. Without it, Back skips past the change entirely.
In new Compose apps you rarely need fragments. When migrating, a fragment can host Compose through a ComposeView, so a team can convert one screen at a time.
The shortcut
For any fragment question, ask "the fragment, or its view?", then "was it added to the back stack?"
Replace
A transaction replaces
PlantListFragmentwithPlantDetailFragmentand callsaddToBackStack.
Drills
Answer fast — trust the rule.
What hosts a fragment?
A fragment is replaced and added to the back stack. What happens to it?
A transaction replaced the list with the detail fragment but did not call addToBackStack. The user presses Back. What happens?
Why is keeping a reference to a fragment's views after onDestroyView a problem?
How can an existing fragment-based app start using Compose?
Remember
- A fragment is a screen-part an activity hosts; its view can die while it lives.
- Ask "the fragment, or its view?" and "was it added to the back stack?"
- New apps can skip fragments; old ones can adopt Compose one screen at a time.
