Android Development

Google's android guide Home Contact

Android Fragments

Fragments allow to divide the user interface of an activity into smaller, reusable components that can be combined in various ways to create a responsive UI for different screen sizes and orientations. Different fragments can be displayed side by side or in separate regions of the larger tablet screen (multi-pane layout). Each fragment has its own layout and UI components, which allows code reusability across different screens. They can also be dynamically added or removed from activities at run time.

There are two ways to add fragments to an activity:
  • By defining the fragment in the activity’s layout file using the tag. This way, the fragment is automatically attached to the activity when the layout is inflated.
  • By defining a container view in the activity’s layout file and then programmatically adding the fragment to the container using the FragmentManager and the FragmentTransaction. This way, there is more more control over when and how to attach the fragment to the activity.

Fragments Lifecycle

Fragments have their own lifecycle methods, which allow to manage the state and behavior of each fragment independently.
  • onAttach(): This method is called when the fragment is attached with an activity. It is the first method to be called in the fragment's lifecycle, and it provides a reference to the hosting activity. It can be used to perform setup that requires access to the activity.
  • onCreate(): This method is called when the fragment is created. It's here one-time initialization is performed, such as initializing variables and setting up resources.
  • onCreateView(): In this method, fragment's layout is inflated and View is returned to represents the fragment's UI. This method is responsible for creating the UI elements.
  • onViewCreated(): This is called after onCreateView() and provides a View object representing the fragment's UI. Additional setup for the UI components here.
  • onActivityCreated(): This method is called after the hosting activity's onCreate() method has completed. Here interaction with the activity or other fragments are accessed in the same activity.
  • onStart(): This method is called when the fragment becomes visible. It signals that the fragment is about to become active and is typically used to start or resume operations that should run when the fragment is visible.
  • onResume():This is called when the fragment is visible and is interacting with the user. It's the appropriate place to start animations, update UI elements, or register for any required callbacks.
  • onPause():This method is called when the fragment is no longer interacting with the user or is about to be covered by another fragment or activity. Pause ongoing operations and unregister from callbacks here.
  • onStop(): This is called when the fragment is no longer visible. Stop or pause any background or UI-related operations that are not necessary when the fragment is not visible.
  • onDestroyView():In this method, clean up the View and resources associated with the fragment's UI. It's called when the fragment is being destroyed but may be recreated later.
  • onDestroy(): This method is called when the fragment is being destroyed. Release any resources held by the fragment, such as references to context or data.
  • onDetach(): This is the last method in the fragment's lifecycle. It's called when the fragment is disassociated from its hosting activity. Perform final cleanup and release any references to the activity.

Note:
There is no direct onRecreate() method available for fragments unlike for activities. The concept of recreating a fragment is different from activity. When the parent activity is recreated due to a configuration change (e.g., screen rotation), its fragments can also be destroyed and recreated along with it. During this process, the fragment lifecycle methods are called, in the same sequence when a fragment is initially created.

Fragments Communication

Fragments can exchange data with each other and with their hosting activity by multiple ways with suitability of a choice depends upon the app's associated functionalities and architectural preferences.
  • Shared ViewModel: Fragments hosted within the same activity can share a ViewModel associated with that activity. This shared ViewModel can hold shared data and state that multiple fragments can use to observe changes to data stored in the ViewModel. To achieve data exchange between fragments using ViewModels, typically LiveData is used as observable patterns. When data changes in one fragment, LiveData notifies other fragments observing the same data.
  • Interfaces: Fragments can define interfaces with callback methods that other fragments or the hosting activity can implement. The first fragment can then call these methods to communicate with other fragments or the activity.Parent activity of fragment sending data implement the interface, and pass data to the second fragment, where interface is implemented to receive the data. Even if the second fragment is hosted within another activity, the parent activity of first fragment can be used as an intermediary for passing data between fragments.
  • Local Broadcasts: Use the Local Broadcast Manager to send and receive broadcasts within your app. Fragments can register to receive local broadcasts and communicate with other fragments or components when a broadcast event occurs.
  • Event Bus Libraries: Third-party event bus libraries like EventBus or Otto allow for event-driven communication between fragments and other components within your app. These libraries simplify communication by decoupling the sender and receiver.
  • SharedPreferences: Fragments can read and write data to SharedPreferences, which is a simple way to store and share key-value pairs across fragments.

Fragments with Jetpack

Jetpack Compose can complement or even replace Fragments in certain scenarios. Fragments are still available and widely used, especially for activities with complex UI's. There has been updates however how Fragments can be used with Jetpack. Fragments are now part of the AndroidX library. Within Jetpack Compose can be used by using the AndroidView composable function. This allows to embed Fragments or other Android views directly within Jetpack Compose UI hierarchy.