Table of contents
- Why Use Fragments?
- How to Create a Fragment
- Adding a Fragment to an Activity
- Replacing a Fragment
- Removing a Fragment
- Conclusion
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:
- Modular UI: You can break down your UI into smaller parts. This makes it easier to manage.
- Reusable UI: You can use the same fragment in different activities. This saves time and effort.
- 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:
- Create a Java Class: This class will extend the
Fragment
class. - 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 calledfragment_example.xml
.
Adding a Fragment to an Activity
To add a fragment to an activity, you need to do the following:
- 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" />
- 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?