Fragment Lifecycle Interview Questions

ANDROID › Lifecycle

Why does Fragment even have two separate lifecycles (the fragment and its view) instead of just one, like Activity has? What real problem does that split solve?

What a strong answer covers: A fragment can stay added to a FragmentManager with its non-view state intact while its view is destroyed and recreated, for example when it's pushed onto the back stack, held offscreen by ViewPager2, or torn down and rebuilt across a configuration change, without the fragment itself being destroyed. The fragment object represents identity and non-view state, the view lifecycle represents whether the inflated hierarchy is currently valid, and Android split them because a fragment can outlive its view but a view can never outlive its fragment. A weak answer just recites onCreateView/onDestroyView without explaining why the split needed to exist.

When would you choose to nest fragments (child fragments) instead of just using multiple top-level fragments in an Activity, and what's a common way nested fragments cause bugs?

What a strong answer covers: Child fragments make sense when a piece of UI genuinely owns and manages its own sub-navigation or sub-state that's meaningless outside its parent, like a tab strip embedded in one screen or a fragment inside a ViewPager2 page. A common bug is using the fragment's parent FragmentManager or the activity's FragmentManager for a transaction that should be a child transaction, which causes id collisions, back-stack confusion, or duplicated transactions when the parent itself gets recreated; the key judgement call is scoping the child strictly to the parent's view lifecycle, not its full lifecycle.

You inherit a codebase where fragments hold view references as class-level vars set in onCreateView and never cleared. What's actually going wrong, and how would you verify and fix it?

What a strong answer covers: Holding the inflated view, or anything view-derived like a RecyclerView adapter or a ViewBinding instance, past onDestroyView leaks the entire view hierarchy because the fragment object survives (on the back stack, or while retained) while its view is torn down and later reinflated, leaving the old view tree pinned in memory. You'd verify it by checking whether onCreateView runs again without a matching field reset, using LeakCanary or simple logging, and fix it by nulling the reference in onDestroyView, typically via a nullable backing property behind ViewBinding, and tying anything view-scoped to viewLifecycleOwner rather than the fragment itself.

Back to Fragment Lifecycle