Skip to the workspace
Pebellslearn by building
Navigation and App Structure  ›  Capstone Project

Fragments — Screens Inside Activities

Fragments 16 minA fragment is a reusable portion of UI with its own lifecycle, hosted by an activity; it is central to older View-based apps and optional in Compose apps.

android / Fragments — Screens Inside Activities

Explore each scene at your own pace.

01 · The rule

The rule

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 in onDestroyView. 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 after onDestroyView leaks 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.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.