Android Fragments

Android Fragments are modular components that represent a portion of a user interface and were introduced in Android 3.0.

Fragments have their own lifecycle, which is closely tied to the lifecycle of the Activity that contains them, and can be added or removed at runtime, allowing for dynamic and flexible UI design.

A Fragment is defined in a Java class that extends the Fragment class and has its own methods to control its behavior and appearance.

To use a Fragment in an Activity, the Activity needs to include a FragmentManager, which is responsible for managing the Fragment’s lifecycle and placement in the Activity’s layout.

Fragments can communicate with each other and with the Activity using interfaces and callback methods, allowing them to pass data or events to other components.



Android Fragment Lifecycle

The lifecycle of an Android Fragment is closely linked to the lifecycle of the Activity containing it.

While Fragments have their own set of lifecycle events, their execution is influenced by the Activity’s lifecycle. The following is the Fragment lifecycle:

MethodsOverview
onAttach()The Fragment’s initial attachment to the Activity triggers this method. Here, the Fragment can get a reference to the Activity that contains it.
onCreate()When the Fragment is first created, this method is called. This is where the Fragment can carry out any initialization it needs to do.
onCreateView()This method is called when it’s time to create the Fragment’s user interface. The Fragment inflates its layout and returns the root View for the Fragment.
onViewCreated()After the Fragment’s View has been created, this method is called. This is where the Fragment can perform additional setup on its View.
onStart()This method is called when the Fragment becomes visible to the user, but is not yet interactive.
onResume()When the Fragment is ready to receive user input, this method is called. The Fragment is interactive and can respond to user input.
onPause()When the Fragment is no longer in the foreground and can no longer respond to user input, this method is called. The Fragment saves any data that needs to be persisted at this point.
onStop()This method is called when the Fragment is no longer visible to the user and is no longer interactive.
onDestroyView()This method is called when the Fragment’s View is being destroyed. The Fragment cleans up any resources that were allocated in onCreateView().
onDestroy()When the Fragment is being destroyed, this method is called. This is where the Fragment performs any final cleanup before it is destroyed.
onDetach()This method is called when the Fragment is being detached from the Activity. Here, the Fragment can release any resources that were tied to the Activity.

Create a Fragment

To create a Fragment, we need to extend the Fragment class and override some of its methods.

Here’s an example of a simple Fragment:

public class MyFragment extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_my, container, false);
}
}

This example shows how to extend the Fragment class in order to create a new Fragment.

To inflate the layout for the Fragment, the onCreateView() method is overridden.

The inflater.inflate() method inflates the layout and returns a View object, which is then returned by the onCreateView() method.

We can add a Fragment to an Activity by using a FragmentManager. Here’s an example of adding a fragment to an activity:

FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
MyFragment myFragment = new MyFragment();
fragmentTransaction.add(R.id.fragment_container, myFragment);
fragmentTransaction.commit();

A FragmentManager can be retrieved by calling getFragmentManager(). Then we create a new FragmentTransaction and add an instance of our Fragment to it. To add the Fragment to the Activity, we commit the FragmentTransaction.

In order to display a Fragment in an Activity, we need to create a layout file containing a container for the Fragment.

A layout file for an Activity containing a Fragment container looks like this:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />

</RelativeLayout>

In the above example, we create a RelativeLayout that contains a FrameLayout with an id of fragment_container.

This is where the Fragment will be displayed.


Types of Fragments

In Android, there are two types of fragments:

TypesOverview
Static FragmentsThese are fragments that are defined in the layout XML file of an activity and are a part of the activity’s layout hierarchy. Once defined, they are static and cannot be removed or replaced at runtime.
Dynamic FragmentsThese are fragments that can be added, removed or replaced at runtime, providing more flexibility to the UI. Dynamic fragments are added to an activity programmatically and are managed by the FragmentManager.

Static fragments provide a more structured approach to building UI, whereas dynamic fragments provide more flexibility and can adapt to changes in the user interface at runtime.

As a Developer you should choose the appropriate type of fragment based on the requirements of your application.


Advantages of using Fragments

AdvantagesOverview
ReusabilityFragments can be reused in different activities, making it easier to develop and maintain an application.
FlexibilityFragments can be combined with other fragments to create a flexible and scalable user interface.
ModularityFragments make it easier to organize code and separate functionality into independent modules.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *