Fragment in Android: Learn About Fragments

It’s about time for learning about Fragment in Android. You will learn about fragments and their lifecycle and more in this post.

Without further ado let us begin with a simple question.

What is fragment in Android ?

Let us put things into perspective by understanding fragments in simple and practical terms.

Fragments are the UI components that are flexible. And they can be reused multiple times. Therefore making the UI a bit more flexible and managed.

Fragments have their own lifecycle, layout and is attached to an activity. Which makes them powerful and much more flexible than an Activity itself.

But the best part about fragment is that you can have as many fragment as you want in a single activity. And this very reason makes the fragment a solid choice for modular UI.

If by this time you’re still confused. Think of fragment as an Activity that acts as a View. Well, that was overly simplified for understanding. But in practical sense fragment will attach itself to the view hierarchy of the Activity.

That is enough introduction for Fragment in Android. Let us see how we can create a new Fragment.

How to create a Fragment in Android ?

Basic usage of the fragment is pretty straight forward.

We can simply create new fragment by right clicking on the package name in Project panel. And then selecting New > Fragment or just follow the instructions below.

You have to create a java class and then extend androidx.fragment.app.Fragment class in that class. Let us see it in action with the code below.

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public class MyFragment extends Fragment {

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        // we have to override this method
        // it is similar to onCreate() of the Activity.
        // and here R.layout.my_fragment is the layout we are going to use
        return inflater.inflate(R.layout.my_fragment, container, false);
    }

}Code language: JavaScript (javascript)

But wait there’s more we have to create the my_fragment.xml file that will contain our fragment’s UI, just like the Activity does.

The code below is the default layout for the fragment generated by Android Studio. Copy the code or create your own as this example might not suit your purpose.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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=".MyFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Hello" />

</FrameLayout>Code language: HTML, XML (xml)

Now that we have successfully created a Fragment in Android. Let us add the fragment to the activity.

Because a Fragment can exist only inside an Activity.

How to show Fragment in Activity ?

Here in this section we will add the Fragment above in a new Activity.

For this, we need to prepare a place for the Fragment to be displayed in our Activity‘s layout.

In the code below for MyActivity in XML design. We are using FrameLayout here because it is a suitable layout for this purpose.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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="0dp"
        android:layout_height="300dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>Code language: HTML, XML (xml)

Now as you can see that we have the ID set as fragment_container. Because this ID will be required to display the Fragment in Activity.

So, here is the code for MainActivity. I’ve added comments there to help you understand it better.

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        showFragment(MyFragment.newInstance());
    }

    private void showFragment(Fragment fragment) {
        getSupportFragmentManager()
                // start this transaction
                .beginTransaction()
                // adds fragment to specified container
                .replace(R.id.action_bar_container, fragment)
                // do not keep in backstack
                .addToBackStack(null)
                // commit to the changes
                .commit();
    }

}Code language: JavaScript (javascript)

That is it, your fragment in Android will appear in the resulting Activity.

Lifecycle of Fragment in Android

Fragment‘s in some sense is similar to an Activity. Because a fragment tries to replicate how an Activity is doing things under the hood.

But it’s much different from an Activity. If you are not familiar to lifecycle of an Activity. I urge you to read this here first: Android Activity Lifecycle: It’s Not That Hard.

You’ll get some idea about what they are and once you understand it it’s same with the Fragment.

The methods are almost same, instead of explaining it one by one. I have put the comments in the code to put things in perspective.

public class MyFragment extends Fragment {

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // called when the Fragment gets created
        // called only once per instance 
        // so do things that are only once done in a Fragment's lifetime
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {

        // this method creates the UI and returns it
        return inflater.inflate(R.layout.my_fragment, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        // will be called after onCreateView()
        // so any logic for view mapping and initialization must be performed here
    }

    @Override
    public void onStart() {
        super.onStart();

        // when the fragment get started
        // will be called every time the app goes to background and comes back 
    }

    @Override
    public void onResume() {
        super.onResume();

        // when the fragment is resumed
    }

    @Override
    public void onPause() {
        super.onPause();

        // when the fragment gets paused
    }

    @Override
    public void onStop() {
        super.onStop();

        // when the fragment is stopped
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

        // is opposite of onCreateView()
        // will be called when the view gets destroyed
    }
}Code language: Java (java)

That is it, you can do whatever you like inside the Fragment and it’s almost as same as an Activity.

And you should prefer use of Fragments instead of Activity today.

Suggested

Parcelable in Android: How to transfer data in-between ?

Create an Android Firebase Project: Simple Guide

Retrofit File Upload using FileProvider ( for Content URIs )

Related Posts