Fragments

June 02, 2026 1 min read

A Fragment is a reusable portion of UI with its own lifecycle, hosted inside an Activity. Modern apps often use one Activity + many Fragments (or fully Compose).

A basic Fragment

class HomeFragment : Fragment(R.layout.fragment_home) {
    override fun onViewCreated(v: View, s: Bundle?) {
        super.onViewCreated(v, s)
        // set up views here, not in onCreate
    }
}

Why fragments?

  • Reuse the same UI on phones and tablets.
  • Power bottom-navigation tabs and view-pager swipes.
  • Swap sections without launching a whole new Activity.
Common mistake: Use viewLifecycleOwner (not the fragment itself) when observing LiveData/Flow in a fragment, or you'll leak the old view.

Summary

Fragments let you compose flexible, reusable screens inside a host Activity, each with its own lifecycle.