Dynamic Fragment in Android
Last Updated :
28 Apr, 2025
Dynamic Fragment is a type of fragment that is defined in an XML layout file and called using FragmentManager class. The FragmentManager class is responsible for managing fragments. It is a part of the Activity and its lifecycle depends on the lifecycle of its container activity. Dynamic Fragments are more responsive and flexible than Static Fragments.
Properties of Dynamic Fragment:
- Defined in Java class by extending FragmentManager class.
- Having a fixed position in the Activity's layout but its content can be changed.
- Can be added, removed, or replaced at runtime.
- Created when the Activity is created and destroyed when the activity is destroyed.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#BDBDBD"
android:padding="15dp"
android:weightSum="3">
<Button
android:id="@+id/btnMessages"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Messages"
android:layout_marginRight="5dp"/>
<Button
android:id="@+id/btnStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="5dp"
android:text="Status" />
<Button
android:id="@+id/btnCalls"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Calls" />
</LinearLayout>
<FrameLayout
android:id="@+id/FL"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Step 3: Working with Activity file (e.g. MainActivity.java)
Here we call fragments using FragmentManager class in Frame Layout.
Java
package com.anas.dynamicfragment;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
// contains dynamic frag + backstack
// of frags + data passing in frags
public class MainActivity extends AppCompatActivity {
String Root_Frag = "root_fagment";
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnMessages, btnStatus, btnCalls;
btnMessages = findViewById(R.id.btnMessages);
btnStatus = findViewById(R.id.btnStatus);
btnCalls = findViewById(R.id.btnCalls);
// default frag
loadFrag(new MessagesFragment(), 0);
btnMessages.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
loadFrag(new MessagesFragment(), 0);
}
});
btnStatus.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
loadFrag(new StatusFragment(), 1);
}
});
btnCalls.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
loadFrag(new CallsFragment(), 1);
}
});
}
// flag 0 for add, 1 for replace
public void loadFrag(Fragment fragment_name, int flag)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
if (flag == 0) {
ft.add(R.id.FL, fragment_name);
fm.popBackStack(Root_Frag, FragmentManager.POP_BACK_STACK_INCLUSIVE);
ft.addToBackStack(Root_Frag);
}
else {
ft.replace(R.id.FL, fragment_name);
ft.addToBackStack(null);
}
ft.commit();
}
}
Step 4: Working with Fragment layout (e.g. fragment_messages.xml)
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"
android:background="#f0f4c3"
android:gravity="center"
tools:context=".MessagesFragment">
<TextView
android:id="@+id/txtMessagesFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Messages Fragment"
android:textSize="22sp"
android:textColor="#cddc39"
android:textStyle="italic|bold"/>
</LinearLayout>
Step 5: Working with Fragment layout (e.g. fragment_status.xml)
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"
android:background="#b2ebf2"
android:gravity="center"
tools:context=".StatusFragment">
<TextView
android:id="@+id/txtUpperFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Status Fragment"
android:textSize="22sp"
android:textColor="#00bcd4"
android:textStyle="italic|bold"/>
</LinearLayout>
Step 6: Working with Fragment layout (e.g. fragment_calls.xml)
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"
android:background="#f8bbd0"
android:gravity="center"
tools:context=".CallsFragment">
<TextView
android:id="@+id/txtUpperFrag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calls Fragment"
android:textSize="22sp"
android:textColor="#e91e63"
android:textStyle="italic|bold"/>
</LinearLayout>
Step 7: Working with Fragment (e.g. MessagesFragment.java)
Java
package com.anas.dynamicfragment;
import android.annotation.SuppressLint;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MessagesFragment extends Fragment {
public MessagesFragment()
{
// Required empty public constructor
}
@SuppressLint("LongLogTag")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_messages, container, false);
return view;
}
}
Step 8: Working with Fragment (e.g. StatusFragment.java)
Java
package com.anas.dynamicfragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class StatusFragment extends Fragment {
public StatusFragment()
{
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_status, container, false);
return view;
}
}
Step 9: Working with Fragment (e.g. CallsFragment.java)
Java
package com.anas.dynamicfragment;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class CallsFragment extends Fragment {
public CallsFragment()
{
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_calls, container, false);
return view;
}
}
Output:
Click on the Messages Button to load Messages Fragment:
Messages Fragment
Click on Status Button to load Status Fragment:
Status Fragment
Click on the Calls Button to load Calls Fragment:
Calls Fragment
Similar Reads
Java Tutorial
Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Java OOP(Object Oriented Programming) Concepts
Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Java Interview Questions and Answers
Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Inheritance in Java
Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Collections in Java
Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling
Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read
Java Interface
An Interface in Java programming language is defined as an abstract type used to specify the behaviour of a class. An interface in Java is a blueprint of a behaviour. A Java interface contains static constants and abstract methods. Key Properties of Interface:The interface in Java is a mechanism to
12 min read
Java Programs - Java Programming Examples
In this article, we will learn and prepare for Interviews using Java Programming Examples. From basic Java programs like the Fibonacci series, Prime numbers, Factorial numbers, and Palindrome numbers to advanced Java programs.Java is one of the most popular programming languages today because of its
8 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read