Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Dynamic Fragment in Android
Next article icon

Dynamic Fragment in Android

Last Updated : 28 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

Output Screenshot
Messages Fragment

Click on Status Button to load Status Fragment:

Status Fragment
Status Fragment

Click on the Calls Button to load Calls Fragment:

Calls Fragment
Calls Fragment

Next Article
Dynamic Fragment in Android

A

anas4112002
Improve
Article Tags :
  • Java
  • Android
Practice Tags :
  • Java

Similar Reads

    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
    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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences