What is a Fragment?
A Fragment is a self-contained UI component that must reside within a 'Host' Activity. Think of a Fragment as a 'Sub-Activity' that has its own lifecycle and receives its own input events. For an Engineering Manager, Fragments are the key to Multi-Pane Layouts—where a single Activity might show a list on the left and details on the right using two separate Fragments.
- The Fragment Lifecycle
The Fragment lifecycle is closely tied to its host Activity, but it has additional states specifically for managing its 'View'. This separation is crucial for a Lead Architect to understand, as a Fragment can exist even when its UI (View) has been destroyed to save memory.
- onAttach(): Called when the fragment is first associated with its activity.
- onCreateView(): The most important method—this is where you inflate the XML layout or initialize the Compose UI for the fragment.
- onViewCreated(): Called immediately after onCreateView. Best place to set up listeners and ViewModels.
- onDestroyView(): Called when the fragment's UI is being removed. This is where you clean up View references.
- onDetach(): The final step—the fragment is no longer associated with the activity.
- FragmentManager and Transactions
To add, remove, or replace Fragments at runtime, you use the FragmentManager to start a FragmentTransaction. These operations are asynchronous and can be added to a 'Back Stack', allowing the user to navigate 'back' through Fragment changes just like they would through Activities.
- Communication: Fragment to Activity
Fragments should be independent. To communicate with their host, we avoid direct references. In 2026, the standard is to use a Shared ViewModel. Both the Activity and its Fragments observe the same ViewModel instance, ensuring that a change in the AI data layer is reflected instantly across the entire UI.
Fragment Role Comparison
| Scenario | Fragment Usage | Flutter Equivalent |
|---|---|---|
| UI Modularity | Fragment (Modular View) | Custom Widget |
| Navigation | FragmentTransaction | Navigator.push() |
| Screen Portion | Partial screen (Pane) | Expanded / Flexible Widget |
| Tab Content | ViewPager2 + Fragments | TabBarView |
| Dialogs | DialogFragment | showDialog() |