Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 104 ยท Legacy Views

Fragments and the Fragment Lifecycle

Learn Android Fragments: FragmentManager and transactions, fragment versus view lifecycle, viewLifecycleOwner, result API, shared ViewModel, ViewPager2 and Navigation, versus Compose.

A Fragment is a reusable piece of UI with its own lifecycle, hosted inside an activity. Fragments were created for tablets (a list pane and a detail pane in one activity) and became the standard way to build single-activity View apps: one Activity holds the window, and each screen is a fragment that is swapped in and out. Even in a Compose world you will meet fragments in older code, in libraries (many dialogs, preference screens and map screens are fragments) and in apps that migrate screen by screen.

The part that bites people is that a fragment has two lifecycles: one for the fragment object and a shorter one for its view. Mixing them up leaks memory and crashes. This lesson covers the manager and transactions, both lifecycles, the right way to observe data, communication between fragments, tabs with ViewPager2, and how the Navigation component and Compose destinations fit. Android classes cannot run here, so the real code is read-only; the TryIts are plain-Kotlin stand-ins that model the back stack and the two lifecycles, and the prose says where they simplify.

Hosting and transactions

An activity hosts fragments in a FragmentContainerView, a layout element that holds the current fragment. The FragmentManager performs transactions: add, replace, remove, show or hide a fragment, optionally recorded on a fragment back stack so the Back button reverses the change.

XML
<!-- read-only example -->
<androidx.fragment.app.FragmentContainerView
    android:id="@+id/container"
    android:name="com.example.app.HomeFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
Kotlin
// read-only example: a replace transaction with a back stack entry
supportFragmentManager.commit {
    setReorderingAllowed(true)
    replace(R.id.container, DetailFragment.newInstance(itemId = 42))
    addToBackStack("detail")
}

Notes that save hours:

  • setReorderingAllowed(true) is recommended on every transaction; it lets the manager optimize and is required for some features.
  • Create fragments with a public no-argument constructor and pass data through arguments (Bundle), not constructor parameters. After a configuration change or process death the system recreates the fragment through its empty constructor and restores the arguments. (A custom FragmentFactory can supply constructor injection, which Hilt uses for you.)
  • replace destroys the old fragment's view; without addToBackStack, Back leaves the activity instead of returning.
  • Use commit (async) normally. After onSaveInstanceState, committing throws, because state can no longer be saved.

The first stand-in models a FragmentManager back stack: replace with addToBackStack, and what Back does. It does not model real Android timing, only the stack rules.

Kotlin A fragment back stack (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The run shows a common surprise. Only the Home-to-Detail transaction was recorded, so when Settings replaced Detail without a back entry, Detail was lost: the first Back press jumps to Home and the second one leaves the activity. Decide per transaction whether Back should return to the screen being replaced.

Two lifecycles

A fragment object can outlive its view. When a fragment is put on the back stack and another replaces it, the old fragment is kept alive (still in memory with its state) but its view is destroyed to save memory. When the user presses Back, the fragment gets a new view created from scratch.

flowchart TD
    A["onAttach"] --> B["onCreate"]
    B --> C["onCreateView / onViewCreated"]
    C --> D["onStart"]
    D --> E["onResume<br/>(visible, interactive)"]
    E --> F["onPause, onStop"]
    F --> G["onDestroyView<br/>view is gone"]
    G -->|"user returns"| C
    G --> H["onDestroy"]
    H --> I["onDetach"]

The fragment lifecycle: onCreate/onDestroy bracket the object, onCreateView/onDestroyView bracket the view. The view part can repeat.

Two consequences follow:

  1. Never hold view references in fragment fields without clearing them. If a field points to a TextView after onDestroyView, the whole old view tree stays in memory. With View Binding, the recommended pattern is a nullable _binding set in onCreateView and cleared in onDestroyView.
  2. Observe with viewLifecycleOwner, not this. The fragment lifecycle is still alive while its view is gone. If you observe with the fragment as the owner, then after Back creates a new view you register a second observer, and updates run twice, or touch a destroyed view.
Kotlin
// read-only example: the standard fragment skeleton
class TaskListFragment : Fragment(R.layout.fragment_task_list) {

    private var _binding: FragmentTaskListBinding? = null
    private val binding get() = _binding!!

    private val viewModel: TaskListViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        _binding = FragmentTaskListBinding.bind(view)
        val adapter = TaskAdapter { task -> viewModel.open(task) }
        binding.list.adapter = adapter

        viewLifecycleOwner.lifecycleScope.launch {
            viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
                viewModel.uiState.collect { state -> adapter.submitList(state.tasks) }
            }
        }
    }

    override fun onDestroyView() {
        _binding = null            // release the views
        super.onDestroyView()
    }
}

The repeatOnLifecycle pattern is the one from Collecting Flows Safely with Lifecycle; in a fragment it must use the view lifecycle. The second stand-in contrasts the two ways of observing across a view being destroyed and recreated.

Kotlin fragment lifecycle vs view lifecycle (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The first run shows the bug: two observers, one of them touching a destroyed view. The second run has exactly one. In the real framework the stale observer would also leak the old view tree.

Talking to other fragments

Fragments should not call methods on each other directly. There are two supported routes.

Shared ViewModel. Two fragments (a list and a detail pane) request the same ViewModel scoped to their activity (or a navigation graph) and communicate through its state, as in ViewModel:

Kotlin
// read-only example
private val shared: SelectionViewModel by activityViewModels()
// or, scoped to a nav graph:
private val shared: CheckoutViewModel by hiltNavGraphViewModels(R.id.checkout_graph)

Fragment Result API. For a one-time answer, such as "the user picked a date", the receiver registers a listener and the sender sets a result under the same key:

Kotlin
// read-only example
// in the screen that wants an answer
setFragmentResultListener("pick_date") { _, bundle ->
    viewModel.onDatePicked(bundle.getLong("millis"))
}
// in the dialog or the picker fragment
setFragmentResult("pick_date", bundleOf("millis" to selectedMillis))

Prefer the shared ViewModel for state that must live as long as a flow, and the result API for one-off events. An Activity interface callback is the legacy way; avoid it in new code.

Tabs with ViewPager2

ViewPager2 shows pages you swipe between, built on RecyclerView internally. Use FragmentStateAdapter when each page is a fragment, and connect a TabLayout with TabLayoutMediator:

Kotlin
// read-only example: three tabs
class HomePagerAdapter(host: Fragment) : FragmentStateAdapter(host) {
    override fun getItemCount() = 3
    override fun createFragment(position: Int): Fragment = when (position) {
        0 -> FeedFragment()
        1 -> SearchFragment()
        else -> ProfileFragment()
    }
}

// in the host fragment's onViewCreated
binding.pager.adapter = HomePagerAdapter(this)         // children belong to the host's child manager
TabLayoutMediator(binding.tabs, binding.pager) { tab, position ->
    tab.text = listOf("Feed", "Search", "Profile")[position]
}.attach()

Pass the host fragment (not the activity) when the pager lives inside a fragment, so pages use the host's child fragment manager and are cleaned up with its view. Pages beyond the neighbors are destroyed, and offscreenPageLimit controls how many are kept. The Compose counterpart is HorizontalPager, covered in Tabs and Pagers.

Manual transactions get tedious. The Navigation component manages them for you. A NavHostFragment in the activity shows destinations from a navigation graph (XML or Kotlin), and a NavController navigates:

XML
<!-- read-only example: res/navigation/main_graph.xml -->
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:startDestination="@id/taskListFragment">

    <fragment android:id="@+id/taskListFragment"
        android:name="com.example.app.TaskListFragment">
        <action android:id="@+id/to_detail" app:destination="@id/detailFragment" />
    </fragment>

    <fragment android:id="@+id/detailFragment"
        android:name="com.example.app.DetailFragment">
        <argument android:name="taskId" app:argType="long" />
    </fragment>
</navigation>
Kotlin
// read-only example
findNavController().navigate(R.id.to_detail, bundleOf("taskId" to task.id))

With the Safe Args Gradle plugin the call becomes type-safe (TaskListFragmentDirections.toDetail(taskId)), and the library handles the back stack, up navigation, deep links and the toolbar. The ideas are exactly the ones in Navigation Compose and Back Stack and Deep Links: destinations, arguments, a back stack, and one controller. Only the destination type changes.

Fragments versus Compose destinations

Topic Fragments Compose
Unit of a screen A Fragment with a view A @Composable function
Lifecycle Fragment and view lifecycles The composition; the owner is the nav back stack entry
Observing data viewLifecycleOwner and repeatOnLifecycle collectAsStateWithLifecycle()
Arguments Bundle or Safe Args Typed routes
Sharing state Shared ViewModel ViewModel scoped to a back stack entry
New app? Only for legacy or library needs Default

You can mix them. A fragment can host a ComposeView (with ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed), as in Compose and Views Interop, and Navigation 2.9 lets Compose destinations coexist with fragments when migrating one screen at a time.

Common mistakes

  • Observing with this instead of viewLifecycleOwner. Duplicate observers and updates to destroyed views.
  • Keeping binding or view fields after onDestroyView. Memory leaks.
  • Passing data through a constructor. The system recreates fragments with the empty constructor; use arguments.
  • Using commit() after state is saved. Throws IllegalStateException; commit earlier or use the Navigation component.
  • Forgetting addToBackStack. Back leaves the activity instead of the previous screen.
  • Giving a nested pager the activity's manager. Use the host fragment so pages are cleaned up with its view.
  • Calling methods on another fragment. Share a ViewModel or use the result API.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A fragment is replaced and added to the back stack. What happens to the old fragment?

    Fragments on the back stack keep their state, but their views are released. When the user returns, onCreateView runs again.
  2. 2. Which lifecycle owner should a fragment use to observe LiveData or collect flows that update its views?

    The view can be recreated while the fragment lives on. viewLifecycleOwner is tied to the view, so observers are removed when the view is destroyed.
  3. 3. How should data be given to a new fragment so it survives recreation?

    The system recreates fragments with the public no-argument constructor and restores the arguments bundle.
  4. 4. Two fragments need to share the currently selected item. Which approach is recommended?

    A shared ViewModel is lifecycle-aware, testable and survives configuration changes, so fragments stay decoupled.
  5. 5. A ViewPager2 lives inside a fragment. What should you pass to FragmentStateAdapter?

    Passing the host fragment makes the pages children of its child fragment manager, so they follow the host's view lifecycle.

Summary

  • A fragment is a UI unit with its own lifecycle, hosted by an activity in a FragmentContainerView and managed by the FragmentManager.
  • Transactions are recorded on a back stack only if you call addToBackStack; use setReorderingAllowed(true).
  • A fragment's object lifecycle is longer than its view lifecycle; clear bindings in onDestroyView and observe with viewLifecycleOwner.
  • Create fragments with empty constructors and pass data through arguments.
  • Share state with a ViewModel scoped to the activity or nav graph; use the Fragment Result API for one-time answers.
  • ViewPager2, FragmentStateAdapter and TabLayoutMediator give swipeable tabs; the Navigation component automates transactions, arguments and deep links.
  • New screens are written as composables; fragments remain for legacy code and libraries.
  • The TryIts are plain-Kotlin stand-ins for the back stack and lifecycles; the Android code is read-only.

Next: Navigation Compose