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.
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. |
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 = ""
)
}
}
}
}
}
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.
Broaden your foundational and advanced Android application development skills across our curriculum:
Master host activity callbacks and process destruction triggers.
Replace manual FragmentTransactions with Jetpack Navigation.
Share ViewModel instances between multiple sibling fragments.
Embed ComposeView inside legacy Fragment layouts.