EDDYMENS

Published 4 months ago

What Are Fragments In Android Development?

Table of contents

A fragment is a small part of an Android app's user interface (UI). Think of it like a mini activity, thus if you know what an Android Activity [→] is. It has its own layout and behavior. But, it cannot live on its own. It must be part of an activity.

Why Use Fragments?

Fragments help us in many ways:

  1. Modular UI: You can break down your UI into smaller parts. This makes it easier to manage.
  2. Reusable UI: You can use the same fragment in different activities. This saves time and effort.
  3. Dynamic UI: You can change fragments at runtime. This makes your app more flexible.

How to Create a Fragment

Creating a fragment is easy. Follow these steps:

  1. Create a Java Class: This class will extend the Fragment class.
  2. Override onCreateView Method: This method sets up the layout for the fragment.

Here is a simple example:

01: public class ExampleFragment extends Fragment { 02: @Override 03: public View onCreateView(LayoutInflater inflater, ViewGroup container, 04: Bundle savedInstanceState) { 05: return inflater.inflate(R.layout.fragment_example, container, false); 06: } 07: }

In this code:

  • ExampleFragment is the name of our fragment.
  • onCreateView method sets up the UI using a layout file called fragment_example.xml.

Adding a Fragment to an Activity

To add a fragment to an activity, you need to do the following:

  1. Add a Container to the Activity Layout: This is where the fragment will go.
01: <FrameLayout 02: android:id="@+id/fragment_container" 03: android:layout_width="match_parent" 04: android:layout_height="match_parent" />
  1. Add the Fragment in the Activity's Code:
01: FragmentManager fragmentManager = getSupportFragmentManager(); 02: FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 03: ExampleFragment fragment = new ExampleFragment(); 04: fragmentTransaction.add(R.id.fragment_container, fragment); 05: fragmentTransaction.commit();

In this code:

  • fragmentManager helps us manage fragments.
  • fragmentTransaction helps us add, replace, or remove fragments.
  • fragment_container is the ID of the container in the activity layout.

Replacing a Fragment

You can replace a fragment with another fragment. This is useful for dynamic UIs. Here is how you do it:

01: AnotherFragment anotherFragment = new AnotherFragment(); 02: fragmentTransaction.replace(R.id.fragment_container, anotherFragment); 03: fragmentTransaction.commit();

In this code:

  • AnotherFragment is a different fragment we want to show.

Removing a Fragment

If you want to remove a fragment, you can do this:

01: fragmentTransaction.remove(fragment); 02: fragmentTransaction.commit();

Conclusion

In summary Fragments make it possible to create reusable UI components.

Here is another article you might like 😊 What Is An Activity In Android Development?