Fragments are a fundamental concept in Android development, introduced in Android 3.0 (Honeycomb) to provide more flexibility and modularity in user interface (UI) design. They allow developers to build more dynamic and flexible UIs that can adapt to various screen sizes, orientations, and device types, such as smartphones, tablets, and foldable devices.
A Fragment is essentially a portion of a UI or behavior that can be embedded within an Activity. While an Activity represents a single screen in an app, a Fragment represents a part of that screen. By using fragments, you can break down complex UIs into smaller, reusable components that can be combined in different ways.
A Fragment is a modular section of an Activity that can have its own UI, lifecycle, and behavior. It is like a small, self-contained part of the UI that can be combined with other fragments to create more complex layouts.
For example, in a tablet app, you might display a list on one side of the screen and detailed information on the other side. On a smartphone, you might combine both in a single screen, using fragments to make the layout adaptable.
Just like Activities, Fragments have their own lifecycle. However, the fragment’s lifecycle is closely tied to the activity’s lifecycle. The fragment’s lifecycle methods can be used to handle initialization, user interactions, and resource cleanup.
Here are the important lifecycle methods for a fragment:
onAttach(Context context): Called when the fragment is first attached to its host activity.onCreate(Bundle savedInstanceState): Called to initialize the fragment. This is where you set up any configuration that needs to persist across fragment recreations.onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState): This method is where the fragment’s layout is inflated. You define the fragment’s UI in this method.onActivityCreated(Bundle savedInstanceState): Called when the host activity’s onCreate() method has been completed. This method is where you can access the activity’s view hierarchy.onStart(): Called when the fragment is visible to the user but not yet active.onResume(): Called when the fragment is active and interacting with the user.onPause(): Called when the fragment is no longer interacting with the user but is still visible.onStop(): Called when the fragment is no longer visible.onDestroyView(): Called when the fragment’s view is destroyed.onDetach(): Called when the fragment is disassociated from the host activity.In Android, fragments are dynamically added or removed from an activity during runtime using fragment transactions. This is done by using the FragmentTransaction class, which allows you to perform actions like:
Here's an example of how to add a fragment dynamically:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, new MyFragment());
transaction.commit();
You can also replace a fragment or add it to the back stack:
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, new NewFragment());
transaction.addToBackStack(null); // Add to back stack for navigation
transaction.commit();
Fragments often need to communicate with their parent Activity or other Fragments. There are several ways to achieve this communication:
Using the Activity: The fragment can call methods in the parent activity to communicate. This is the most common way to send data from a fragment to its activity.
Example:
// Inside the Fragment
((MyActivity) getActivity()).onFragmentMessage("Hello from Fragment!");
Using an Interface: For better decoupling, fragments can define an interface to communicate with their parent activity. This method allows for cleaner communication and greater flexibility.
Example:
public interface OnFragmentInteractionListener {
void onFragmentMessage(String message);
}
// In Fragment:
OnFragmentInteractionListener listener = (OnFragmentInteractionListener) getActivity();
listener.onFragmentMessage("Hello from Fragment!");
Fragments can be passed arguments when they are created. These arguments are stored in a Bundle and can be retrieved later in the fragment.
For example, to pass arguments to a fragment:
Bundle bundle = new Bundle();
bundle.putString("key", "value");
MyFragment fragment = new MyFragment();
fragment.setArguments(bundle);
// Now you can add the fragment
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.fragment_container, fragment);
transaction.commit();
To retrieve the argument in the fragment:
String value = getArguments().getString("key");
Fragments are a powerful feature of Android development that allow for more flexible, modular, and dynamic UI designs. They help developers create applications that can adapt to different screen sizes, orientations, and device types. Understanding how to use fragments, manage their lifecycle, and facilitate communication between fragments and activities is essential for building high-quality Android applications that provide a smooth user experience across devices.
Open this section to load past papers