The Wayback Machine - https://web.archive.org/web/20240819102611/https://www.geeksforgeeks.org/dynamic-fragment-in-android/
Open In App

Dynamic Fragment in Android

Last Updated : 19 Mar, 2023
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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 
   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 
   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
   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 
   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



Similar Reads

Fragment to Fragment Communication in Android using Shared ViewModel
If there are two or more fragments in an activity, they need to communicate and share the data between them. The traditional way of sharing the data between the two fragments is implementing the callback using an interface that is cumbersome and may throw exceptions. But the modern way of doing that is using shared ViewModel. So in this article, it
6 min read
How to Implement Google Map Inside Fragment in Android?
In Android, the fragment is the part of 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 UI flexibility on all devices improves the user experie
4 min read
How to Implement RecyclerView in a Fragment in Android?
In Android, a fragment is a modular section of a user interface that can be combined with other fragments to create a flexible and responsive application. A fragment represents a behavior or a portion of the user interface in an Activity, which can be reused in different activities or layouts. It has its own lifecycle and can receive input events a
12 min read
How to Create a New Fragment in Android Studio?
Android Studio is the official integrated development environment for Google's Android operating system, built on JetBrains' IntelliJ IDEA software and designed specifically for Android development. You can Develop Android App using this. Here, We are going to learn how to create a new Fragment in Android Studio. A Fragment is a piece of an activit
2 min read
Difference Between a Fragment and an Activity in Android
An Activity is a user interface component that is mainly used to construct a single screen of the application and represents the main focus of attention on a screen. An activity can host one or more fragments at a time. Fragments, as tablets emerged with larger screens, are reusable components that are attached to and displayed within activities. I
2 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 &lt;fragment&gt; tag in XML layout file.Having a fixed position in the Activity's layout.Cannot be removed or replaced at ru
2 min read
How to Save Fragment States with BottomNavigationView in Android?
In Android applications, Activities and Fragments are from the foundation of the UI layer. It is now standard practice to load the UI with multiple fragments. For example, Instagram, Twitter, and a slew of other well-known apps. Imagine browsing some tweets in the Twitter app's HomeFragment, navigating to the search screen, and then returning to th
4 min read
How to Get Current Location Inside Android Fragment?
A Fragment is a piece of an activity that enables 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 layouts and their logic. You can build single-pan
5 min read
How to Implement GridView Inside a Fragment in Android?
A GridView is a versatile and efficient widget that allows you to display items in a grid-like fashion, perfect for presenting images, icons, or any structured data. Fragments, on the other hand, are essential components for building flexible and modular user interfaces. They enable the creation of reusable UI components that can be combined to cre
5 min read
How to Create Fragment Using Bottom Navigation in Social Media Android App?
This is the Part 2 of "Build a Social Media App in Android Studio" tutorial, and we are going to cover the following functionalities in this article: We are going to Create Bottom Navigation with 5 Fragments (Home, Users, AddBlog, ChatList, Profile).On HomeFragment we will be Showing all the added blogs.In the UsersFragment, we will be showing all
4 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 UI flexibility on all devices improves the user exp
9 min read
How to Pass Data from Dialog Fragment to Activity in Android?
In many applications, you may have seen that whenever we have to make choices some kind of elevated dialog box appears and ask the user for some input or choice. In this article, we are going to see the same that how we can pass data from a Dialog Box to activity in Android Studio. What we are going to build in this article?In this article, we will
4 min read
How to Send Data From Activity to Fragment in Android?
Prerequisites: Introduction to Activities in AndroidIntroduction to Fragments in AndroidIn Android, a fragment is a portion of the user interface that can be used again and again. Fragment manages its own layout and has its own life cycle. Since fragment is a small portion of the bigger user interface, it can only be initialized inside an activity
5 min read
How to Implement Tabs, ViewPager and Fragment in Android using Kotlin?
In some Android apps, Tabs are used, which allows developers to combine multiple tasks (operations) on a single activity. On the other hand, it provides a different look to that app. It is also possible to provide a different feel like left and right swipes by using ViewPager. And to implement this topic, a few terms are required such as ViewPager,
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 mark things as completed by the user in task mana
3 min read
How to Create Dynamic WebView in Android with Firebase?
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView which we have to load. So if you are looking for loading a website into your app which can be changed dyna
6 min read
How to Create Dynamic PDF Viewer in Android with Firebase?
If you are creating apps for students or for educational purposes then you need to add some PDF files for displaying some data inside our app. These PDF files are updated on regular basis. For loading this PDF from the server we prefer to use PDF Viewer which will load the PDF from the URL in Android. Inside this, we add the URL for PDF inside our
8 min read
How to Create a Dynamic Video Player in Android with Firebase Realtime Database?
Most of the apps use the video player to display so many videos inside their application. So for playing the video the app plays the video from its video URL. But what if we want to update that video on a real-time basis. So, in that case, we have to update our database and then later on we have to update our APK. So this is not an efficient way to
8 min read
How to Create a Dynamic Audio Player in Android with Firebase Realtime Database?
Many online music player apps require so many songs, audio files inside their apps. So to handle so many files we have to either use any type of database and manage all these files. Storing files inside your application will not be a better approach. So in this article, we will take a look at implementing a dynamic audio player in our Android app.
7 min read
How to Create Dynamic Horizontal RecyclerView in Android using Firebase Realtime Database?
HorizontalRecyclerView is seen in many apps. It is generally used to display the categories in most apps and websites. This type of RecyclerView is mostly seen in many E-commerce apps to indicate categories in the app. As we have already seen in Amazon Shopping App. So in this article, we will take a look at creating a Dynamic Horizontal Recycler V
7 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 organizations with branding and establishing ident
3 min read
How to Implement Dynamic TabLayout in Android?
In this article, we will learn about how to add Dynamic TabLayout with ViewPager in an app. TabLayout provides a horizontal layout to display tabs. Here we will be just specifying the number of tabs we want to have. WhatsApp, Facebook, etc are a very good example of TabLayout with ViewPager. A sample GIF is given below to get an idea about what we
5 min read
How to Use Dagger in Dynamic Feature Module in Android?
In our previous article, we learned how to set up dagger in an Android project with a multi-module architecture. Click here to see how we can use Dagger in Multi-Module Architecture. We will be expanding on the project that we worked on in our previous project. But first, we must learn how to create and configure a dynamic-feature module. Click her
3 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 to get an idea about what we are going to do in t
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. A sample video is given below to get an idea about
7 min read
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 idea about what we are going to do in this article.
8 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. [video mp4="https://media.geeksforgeeks.org/wp-co
8 min read
Android Jetpack Compose - Create Dynamic WebView using Firebase Realtime Database
Converting a website into an application seems like a basic task to do on Android. With the help of WebView, we can show any webpage in our Android Application. We just have to implement the widget of WebView and add the URL inside the WebView that we have to load. So if you are looking for loading a website into your app which can be changed dynam
8 min read
How to Generate Dynamic Multiple Buttons in Android?
In Android Studio, buttons are graphical user interface (GUI) elements that users can click or tap to perform an action. Buttons are typically represented by a rectangular or rounded rectangular shape with a label or an icon. In this article, we will learn to make dynamic multiple buttons in android studio. By which we can make unlimited buttons in
3 min read
Android Jetpack Compose - Dynamic Progress Bar with Text
Jetpack Compose is Android’s modern toolkit for building native UI. It simplifies and accelerates UI development on Android bringing your apps to life with less code, powerful tools, and intuitive Kotlin APIs. It makes building Android UI faster and easier This toolkit offers a wide range of pre-built UI components, allowing developers to easily de
6 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg