Add fragment programmatically in android

In this post, we will learn to add a fragment to an activity dynamically. And if you want to learn about adding a fragment via XML then, here’s the link to my post on adding a fragment to an activity via XML – https://developerxon.com/2022/06/24/how-to-add-a-fragment-to-an-activity-via-xml/

How to add fragment dynamically in android?

First, create a new android project. Then, change the layout of the activity like this –

activity_main.xml

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

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/fragment_container_view"
        android:layout_width="match_parent"
        android:layout_height="187dp"
        android:layout_gravity="center"
        android:layout_marginStart="20dp"
        android:layout_marginEnd="20dp" />

</LinearLayout>

Here, I have added a FragmentContainerView. It is like a container for the fragments. For example, if you have two or more fragments you will use this container to replace the fragments. During runtime, you can add, remove or replace a fragment using fragment transactions.

Now create a layout for the fragment like this –

example_fragment.xml

<?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"
    android:background="#92F3C9"
    tools:context=".ExampleFragment">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:text="Hi there! I'm a fragment"
        android:textColor="#43CDE4"
        android:textSize="30sp" />

</FrameLayout>

Here, I added a TextView inside a FrameLayout.

Create a java file for the fragment like this –

FragmentExample.java

package com.example.addfragmentprogramatically;

import android.os.Bundle;

import androidx.fragment.app.Fragment;

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

public class ExampleFragment extends Fragment {

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


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

Simply inflate the layout inside the onCreateView() method.

Now, Let’s add the fragment to the activity. Change the code inside the MainActivity.java file like this –

MainActivity.java

package com.example.addfragmentprogramatically;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.fragment_container_view, ExampleFragment.class, null)
                    .commit();
        }
    }
}

You know that the activity is recreated when a configuration change occurs. That means the code to create the fragment inside the onCreate will also run when the activity is recreated. But, we don’t want that because the fragment is automatically restored from the savedInstanceState. How can we ensure that the fragment is added only once, when the activity is first created? The answer is to check if the savedInstanceState is null. When the activity is recreated after the configuration change, then, this savedInstanceState will not be null, then the code inside the if block won’t run and the fragment will not be added a second time.

Inside the If bloc, get an instance of the FragmentManager. The FragmentManager is used to manage the fragments that you add to the activity. Then, use the instance of the FragmentManager to begin the transaction by calling its beginTransaction() method. Then call the fragment transaction’s add() method to add the fragment to the activity.

To finish the transaction, call the commit() method of the fragment transaction. This applies the changes that is specified.

Output:

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: