Fragments and their lifecycle
Why it matters
- A Fragment has two lifecycles: the Fragment itself and its view. Mixing them up is the number one Fragment bug.
- Leaks and "the event fired twice" bugs after pressing Back almost always trace to this.
- Many production apps still use Fragments: Navigation component, bottom sheets, dialogs,
ComposeViewhosts. You will meet them in legacy code and in interviews. - "Why
viewLifecycleOwner?" is a favourite interview question.
The simple explanation
Think of a theatre play. The actor is the Fragment instance. The stage set is the view.
- When the scene changes, the crew removes the stage set. The actor goes backstage and keeps their script and notes.
- When the scene comes back, the crew builds a new set. The same actor walks on.
- If the actor is sent home for good, both are gone.
So the instance can live longer than its view. That happens when a Fragment is on the back stack.
The real names:
| Callback | Meaning |
|---|---|
onAttach | attached to the host Activity, context is available |
onCreate | the instance is created, there is no view yet |
onCreateView / onViewCreated | build the view, then set up listeners and collect flows |
onStart / onResume | visible, then in the foreground |
onPause / onStop | losing focus, then hidden |
onDestroyView | the view is going away: clear your binding |
onDestroy | the instance is finished (not called when it only sits on the back stack) |
onDetach | no longer attached to the Activity |
The view has its own viewLifecycleOwner. It is valid only between onCreateView and onDestroyView. Asking for it outside that window throws an IllegalStateException.
Notes
- Instance and view are separate. On the back stack,
onDestroyViewruns butonDestroydoes not. The fields survive. The view and everything that points at it must be released. replace()withaddToBackStack()keeps the old Fragment instance.replace()without it destroys the old Fragment.- Observe LiveData and collect Flows with
viewLifecycleOwner, notthis. Withthis, each return from the back stack adds one more observer to a Fragment that never died. - Clear view binding in
onDestroyView. A Fragment on the back stack that still holds the binding keeps the whole old view hierarchy in memory. - Collect flows with
repeatOnLifecycle(STARTED)onviewLifecycleOwner, so collection stops when the view is not visible. - Pass data with the
argumentsBundle or Navigation arguments. The defaultFragmentFactoryrecreates a Fragment with its empty constructor, so constructor parameters are lost, and the app crashes if there is no empty constructor. A customFragmentFactoryis the only way around that. - ViewModel scope:
by viewModels()is per Fragment,by activityViewModels()is shared with the host Activity,by navGraphViewModels()is shared inside one navigation graph. - Talk between Fragments with the Fragment Result API (
setFragmentResultandsetFragmentResultListener) or a shared ViewModel.setTargetFragmentis deprecated. - Use
childFragmentManagerfor Fragments nested inside a Fragment. UseparentFragmentManagerfor siblings. - A transaction committed after
onSaveInstanceStatethrowsIllegalStateException. Commit earlier, or usecommitAllowingStateLossonly when losing the change is acceptable. - Inside a Fragment, host a
ComposeViewwithViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed, so the composition is disposed with the view, not the Fragment.
Code example
A profile screen with view binding. The binding is cleared with the view. The flow is collected for the view's lifetime only.
class ProfileFragment : Fragment(R.layout.fragment_profile) {
// Only valid between onViewCreated and onDestroyView.
private var _binding: FragmentProfileBinding? = null
private val binding get() = _binding!!
// One ViewModel per Fragment; it survives rotation.
private val viewModel: ProfileViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
_binding = FragmentProfileBinding.bind(view)
binding.retryButton.setOnClickListener { viewModel.load() }
// viewLifecycleOwner, not "this": stops with the view.
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.state.collect { render(it) }
}
}
}
private fun render(state: ProfileState) {
binding.name.text = state.name
}
override fun onDestroyView() {
_binding = null // release the old view hierarchy
super.onDestroyView()
}
}Why _binding is nullable: the property is only safe to read while the view exists. After onDestroyView a stale read crashes early instead of silently using a dead view. That is the point.
In production
- Users open a list, tap an item and press Back. The next network error shows two "Network error" dialogs, and every further round trip adds one more.
- The Fragment looked fine in a single run.
- Cause: the Fragment observed a LiveData with
thisas the owner inonViewCreated. When the user returned from the back stack,onViewCreatedran again, but the Fragment instance was still alive. Each return added another observer.
- Reproduce it: open the screen, navigate forward, press Back, repeat. Add a log line in the observer and count the lines.
- Change the owner to
viewLifecycleOwner. Observers are then removed with the view. - Prefer one-off UI events as part of state that is marked as handled, so a rebuilt view does not replay them.
- Turn on LeakCanary in debug builds. It reports a Fragment view that stays in memory after
onDestroyView.
- Memory use grows while users move between screens. An out-of-memory crash appears after long sessions on cheaper devices.
- Cause: the Fragment kept
bindingas a plain field and never cleared it. After navigating forward, the old view hierarchy, with its images, stayed reachable from the Fragment on the back stack.
- Set the binding to null in
onDestroyView. - Also clear adapters set on a
RecyclerViewand other view references you stored in fields. - Check with a heap dump or LeakCanary after navigating away and back.
Common mistakes
- Observing with
thisinstead ofviewLifecycleOwner. It gives duplicate observers after the back stack. - Reading
bindingafteronDestroyView. A late callback from a coroutine or listener crashes. Cancel work with the view lifecycle. - Passing data through a constructor. The default factory recreates the Fragment with its empty constructor, so the data is lost, or the app crashes if there is no empty constructor. Use
arguments. - Using the Activity as a shared bus. Casting the host to a listener interface couples the Fragment to one Activity. Use the Fragment Result API or a shared ViewModel.
- Touching views in
onCreate. There is no view yet. UseonViewCreated. - Assuming
onDestroyruns when the user navigates away. With the back stack, onlyonDestroyViewruns.
Interview questions
Answer out loud first. Then reveal the answer and compare it at each depth.
“What is the difference between a Fragment's lifecycle and its view's lifecycle?”
“Why should you observe LiveData with viewLifecycleOwner?”
“How do two Fragments communicate?”
Quiz
A Fragment is replaced with addToBackStack. Which callback runs on the old Fragment?
Which owner should you use to collect a Flow in onViewCreated?
Where should view binding be set to null?
What is the safe way to give a Fragment its start data?
0 of 4 answered
Mini task
Build two Fragments, ListFragment and DetailFragment, in one Activity. Navigate List to Detail with replace and addToBackStack.
- Add a log line to
onCreate,onCreateView,onDestroyViewandonDestroyinListFragment. - Observe a LiveData or StateFlow in
ListFragmentthe wrong way (ownerthis) and log each emission. - Go to Detail, press Back, and repeat three times. Count the log lines.
- Fix the owner to
viewLifecycleOwnerand count again.
You are done when you can explain which callbacks ran at each step and why the wrong version logged more lines each time.