Fragment Lifecycle Interview Questions
ANDROID › Lifecycle
What are the main Fragment lifecycle callbacks, and how do they relate to the host Activity's lifecycle?
What a strong answer covers: onAttach, onCreate, onCreateView, onViewCreated, onStart, onResume, then onPause, onStop, onDestroyView, onDestroy, onDetach. A fragment's lifecycle can't be further along than its host's, and the FragmentManager moves fragments through states as the activity moves and as transactions run.
Why does a Fragment have a separate view lifecycle, and when should you use viewLifecycleOwner instead of this?
What a strong answer covers: A fragment can outlive its view: on the back stack, onDestroyView runs but the fragment instance stays, and the view is recreated when you go back. Observing LiveData or collecting flows with 'this' as the owner keeps the observer alive past the view and registers duplicates when the view is recreated. Use viewLifecycleOwner for anything touching views, from onViewCreated.
How do you avoid leaking a view binding in a Fragment?
What a strong answer covers: The binding holds the whole view hierarchy, but the fragment outlives its views on the back stack. Keep a nullable _binding set in onCreateView and set it to null in onDestroyView, with a non-null getter used only between those two. Alternatively, use a delegate tied to viewLifecycleOwner.
How should fragments communicate with each other and with their activity?
What a strong answer covers: Avoid direct references and casting the activity to an interface. Options: a shared ViewModel scoped to the activity or a navigation graph (activityViewModels or navGraphViewModels) for shared state; the Fragment Result API (setFragmentResult and setFragmentResultListener) for one-off results; and Safe Args or arguments to pass input. Each survives configuration changes.
What's the difference between add, replace, commit, commitNow and commitAllowingStateLoss, and when do you hit 'Can not perform this action after onSaveInstanceState'?
What a strong answer covers: add puts a fragment on top; replace removes existing fragments in the container first. commit schedules the transaction asynchronously; commitNow runs it synchronously (not allowed with addToBackStack). After the state is saved, a commit would be lost if the process died, so the FragmentManager throws IllegalStateException. Causes: committing from an async callback after onStop. Fixes: only commit while started (lifecycle-aware collection), or commitAllowingStateLoss when losing the transaction is acceptable.