What Is an Android Fragment?
A Fragment is a modular, reusable component that represents a portion of an activity’s UI. It has its own lifecycle and state, making it ideal for dynamic and flexible UI structures.
Why Use Fragments (Especially on Tablets)?
- Dual-panel interfaces: On large screens, two or more views (like list + detail) can appear side-by-side using multiple fragments.
- Efficiency: One activity can manage several fragments instead of launching multiple activities.
Fragment Arguments vs Instance Variables
- Never pass data via the constructor—Android may recreate fragments during lifecycle changes.
- Use
setArguments(Bundle)
immediately after instantiation and before attaching to the hosting activity. These arguments persist across the fragment lifecycle.
Fragment Manager & Lifecycle Methods
The Fragment Manager handles fragment transactions and lifecycle. Lifecycle callbacks occur in this order:
Callback | Description |
---|---|
onAttach() | Fragment attaches to activity context |
onCreate() | Initialize non-UI resources |
onCreateView() | Inflate or return UI view (null for headless fragments) |
onActivityCreated() | Activity’s onCreate is complete—start using views |
onStart() → onResume() | Fragment becomes visible and interactive |
onPause() → onStop() → onDestroyView() | Cleanup UI resources |
onDestroy() | Final cleanup before GC |
onDetach() | Fragment detaches from activity |
Interaction Scenarios
Back Button Press (Without Backstack)
- Fragment and activity pause
- UI destroyed (
onDestroyView()
) - Fragment destroyed and detached
- Activity finishes
Device Lock/Unlock
- Locking pauses and stops activity/fragment
- Unlocking restarts the activity, followed by fragment (
onStart()
→onResume()
)
If Fragment Created in Activity’s onCreate()
- Activity → Fragment attaches/creates → Views inflate → UI ready for interaction
If Created in onResume()
- Fragment lifecycle callbacks run in full sequence since activity methods are already complete
Practical Tip
- Always use
setArguments()
for data passing - Control UI composition and state transitions via proper lifecycle positioning
- Avoid nested fragments unless managing complex UI flows