Android Fragments
Fragments allow to modularize an activity's user interface into smaller, reusable components that can be combined in flexible ways. This enables responsive designs for different screen sizes and orientations. On larger screens like tablets, multiple fragments can be displayed simultaneously in a multi-pane layout. Each fragment has its own layout and lifecycle, encouraging code reusability across the app. Fragments can be dynamically added, replaced, or removed from an activity at runtime.
Adding Fragments to an Activity
Fragments can be added to an activity using two primary methods:
-
Using the
<fragment>tag: Declare the fragment in the activity’s XML layout. It is automatically instantiated and attached when the layout is inflated. -
Using a container view: Define a container (e.g.,
FrameLayout) in the activity's layout and programmatically add the fragment usingFragmentManagerandFragmentTransaction. This method offers more flexibility.
Fragment Lifecycle
Like activities, fragments follow a well-defined lifecycle, allowing developers to manage their state and resources appropriately. Key lifecycle methods include:
- onAttach(): Called when the fragment is first attached to its host activity.
- onCreate(): Initialize non-UI components.
- onCreateView(): Inflate the fragment's layout and return its root view.
- onViewCreated(): Called after the view has been created; ideal for binding views or observing data.
- onActivityCreated(): Deprecated – previously used for activity-level initialization.
- onStart(): The fragment becomes visible to the user.
- onResume(): The fragment is actively running and interactive.
- onPause(): The fragment is partially obscured or transitioning out.
- onStop(): The fragment is no longer visible.
- onDestroyView(): Clean up the fragment’s view hierarchy.
- onDestroy(): Final cleanup of fragment state.
- onDetach(): The fragment is detached from its host activity.
Note: Fragments do not have an onRecreate() method. When the parent activity is recreated
(e.g., during a configuration change), the fragments are destroyed and recreated automatically, following the full lifecycle.
Fragment Communication
Fragments can communicate with each other and with their host activity through several patterns:
- Shared ViewModel: Use a ViewModel scoped to the activity to hold shared state. Fragments can observe LiveData or StateFlow for reactive data exchange.
- Interfaces: Define an interface in the fragment that the activity implements to handle events or data passing.
-
Fragment Result APIs: Use
FragmentManager.setFragmentResult()andsetFragmentResultListener()to pass data between fragments. - Event Bus Libraries: Tools like EventBus or LiveEventBus can decouple communication, though their use is often discouraged in modern architectures unless justified.
- SharedPreferences or Bundle Arguments: Useful for simple, persistent key-value storage or passing arguments at creation time.
Fragments with Jetpack Compose
Jetpack Compose offers a declarative UI framework that reduces or eliminates the need for traditional fragments in many modern Android applications. However, fragments remain relevant in the following scenarios:
- Legacy Code Integration: Many projects still rely on fragments. Compose can be introduced gradually alongside them.
- Multi-pane Layouts: In-app multi-pane UIs, such as those used on tablets and foldables, can be implemented using either fragments or composables. Jetpack Compose offers a fully declarative way to build such layouts without requiring fragments.
-
Third-Party Library Compatibility: While most modern libraries are becoming Compose-friendly, some still rely on the traditional
View system. Compose allows integration through the
AndroidViewcomposable, but for more complex interactions, fragments may still serve as a bridge when working with non-Compose UI components. -
Navigation Component Support: Compose uses its own declarative
NavHostand navigation system, where routes (destinations) are explicitly defined to manage complex screen flows and transitions within Compose-based apps.