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:
Click on Status Button to load Status Fragment:
Click on the Calls Button to load Calls Fragment: