Dynamic Fragment in Android
Last Updated :
24 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
Dynamic ImageSwitcher in Android
Android ImageSwitcher is a user interface widget that provides a smooth transition animation effect to the images while switching between them to display in the view. In this article, we will take a look at How to Create a Dynamic Image Switcher in Android. A sample video is given below to get an id
8 min read
Dynamic Spinner in Android
Many times in android applications we have to create any view dynamically without writing any XML code. For that, we can create our view using our Kotlin or Java file. In this article, we will take a look at How to Dynamically create a spinner in an android application. A sample video is given below
6 min read
Dynamic Switch in Android
Switch is a widget used in android applications for performing two-state operations such as on or off. The switch provides functionality where the user can change the settings between on and off using the switch. In this article, we will take a look at How to Create a Switch dynamically in Android.
7 min read
Static Fragment in Android
Static Fragment is a type of fragment that is defined in an XML layout file only. It is a part of the Activity and its lifecycle depends on the lifecycle of its container activity. Properties of Static Fragment: Defined using <fragment> tag in XML layout file.Having a fixed position in the Act
2 min read
Fragment Lifecycle in Android
In Android, the fragment is the part of the Activity that represents a portion of the User Interface(UI) on the screen. It is the modular section of the Android activity that is very helpful in creating UI designs that are flexible in nature and auto-adjustable based on the device screen size. The U
8 min read
Dynamic Splash Screen in Android
A Dynamic Splash screen is a more personalized image or graphic that is displayed when an application is loaded or launched. Dynamic Splash Screen consists of animation or moving graphics. It appears for a fraction of a second. It creates a sense of anticipation or excitement for the user and helps
3 min read
Dynamic TextSwitcher in Android
Text Switcher is a widget in android that contains multiple text views and we can display one text at a time in it. In this article, we will take a look at How to implement a Dynamic Text Switcher in Android. A sample video is given below to get an idea about what we are going to do in this article.
8 min read
Dynamic CheckBox in Android with Examples
Android offers a wide variety of widgets for user interactions and CheckBox is one among them. CheckBox is a special kind of button with two states that can be either checked or unchecked. They serve as a simple tool to gather information from the user without much hassle. They are generally used to
3 min read
Introduction to Fragments | Android
Fragment is a piece of an activity that enables a more modular activity design. A fragment encapsulates functionality so that it is easier to reuse within activities and layouts. Android devices exist in a variety of screen sizes and densities. Fragments simplify the reuse of components in different
5 min read
Ball Tapping Game in Android
Android is an open-source operating system, based on the Linux kernel and used in mobile devices like smartphones, tablets, etc. Further, it was developed for smartwatches and Android TV. Each of them has a specialized interface. Android has been one of the best-selling OS for smartphones. Android O
4 min read