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.