What is a Fragment in Android?

Instruction: Explain what Fragments are and how they are used in Android applications.

Context: Assess what a Fragment owns, its lifecycle and separate view lifecycle, and its use in adaptive interfaces. Distinguish FragmentManager/transactions for UI structure from shared ViewModels or Fragment Result APIs for communicating data.

Updated

Official answer

A Fragment is a reusable controller hosted by an activity or another fragment. It has its own lifecycle and may own a view hierarchy. A list/detail interface can show one destination in a narrow window and two panes when sufficient space is available.

FragmentManager owns fragment instances and the back stack. A FragmentTransaction adds, replaces or removes fragments; that changes navigation/UI structure rather than providing a general data channel. Use a shared ViewModel scoped to the intended activity or navigation owner for shared state, or the Fragment Result API for a one-time result. Both participants must use the intended common owner; separate fragment-scoped ViewModels are different instances.

The fragment and its view have different lifetimes. The fragment can remain on the back stack after its old view is destroyed. Observe view-related data using viewLifecycleOwner, and clear view bindings/listeners that retain the old view in onDestroyView. Recreate the view from retained or saved state instead of keeping a reference to the previous activity.

For a filter dialog, return the selected filter and let the list's state owner update the results. Test navigating away/back, rotation and process recreation, ensuring that results reach the intended owner and no callback updates a destroyed view.

Fragment lifecycle, Fragment communication

Related Questions