Android Fragments: Lifecycle, FragmentManager & Backstack

A Fragment represents a modular, reusable portion of an Activity's user interface. Introduced in Android 3.0 (Honeycomb) to support multi-pane tablet layouts, Fragments have their own independent lifecycle, receive their own input events, and can be added, removed, or replaced dynamically at runtime while the host Activity is running.

The Fragment Lifecycle vs. Activity Lifecycle

A Fragment's lifecycle is inextricably tied to its host Activity. In addition to Activity callbacks, a Fragment introduces view-specific lifecycle callbacks:

Fragment Callback Description & Purpose
onAttach(context) Called when the Fragment is first bound to its host Activity Context.
onCreate(savedInstanceState) Initializes the Fragment instance (receives arguments bundle).
onCreateView() Creates and returns the View hierarchy (or ComposeView) associated with the Fragment.
onViewCreated(view, savedInstanceState) Called immediately after the view is created. Ideal place for setting up adapters, observers, and listeners.
onDestroyView() Called when the view hierarchy is removed. View references must be cleared here to prevent memory leaks.
onDetach() Called when the Fragment is completely disassociated from the host Activity.

Embedding Jetpack Compose inside a Fragment (Modern Interop)

In modern Android development, most existing Fragment-based projects migrate to Compose by returning a ComposeView inside onCreateView():

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.ViewCompositionStrategy
import androidx.fragment.app.Fragment

class ProfileFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return ComposeView(requireContext()).apply {
            // Dispose the Composition when the Fragment's LifecycleOwner is destroyed
            setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
            setContent {
                VeewomTheme {
                    StudentProfileCard(
                        name = "Alex Johnson",
                        course = "BCA Semester IV",
                        avatarUrl = ""
                    )
                }
            }
        }
    }
}

Best Practice: DisposeOnViewTreeLifecycleDestroyed

A Fragment can be pushed to the backstack where its View is destroyed while the Fragment instance remains alive. Setting ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed ensures Jetpack Compose cleans up its internal composition nodes when onDestroyView() fires, preventing memory leaks.

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between an Activity and a Fragment?

An Activity is an independent operating system component declared in AndroidManifest.xml that runs in its own window. A Fragment is a reusable sub-component that must be hosted inside an Activity and cannot exist independently.

Q2. What is FragmentContainerView and why is it preferred over ?

`FragmentContainerView` is a specialized layout designed specifically for hosting Fragments. It fixes animation coordination bugs, ensures proper Fragment transactions, and handles window insets correctly compared to the legacy `` tag.

Q3. What does addToBackStack() do in a FragmentTransaction?

When you call `transaction.addToBackStack(null)`, Android records the replacement on the navigation backstack. When the user presses the system back button, Android reverses the transaction (re-showing the previous Fragment) instead of closing the entire Activity.

Explore Related Android Development Classes & Next Steps

Broaden your foundational and advanced Android application development skills across our curriculum:

Activity Lifecycle & States

Master host activity callbacks and process destruction triggers.

Navigation Component & Safe Args

Replace manual FragmentTransactions with Jetpack Navigation.

ViewModel State Management

Share ViewModel instances between multiple sibling fragments.

XML Views vs. Jetpack Compose

Embed ComposeView inside legacy Fragment layouts.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Reddit

You may also like this!