Dynamically Add Fragment in Android Using Android Studio

Introduction

 
This article explains how to create Fragments dynamically in Android using Android Studio.
 
Fragments are more often used for user interface purposes. Fragments are used when the user wants to see two different views of two different classes on the same screen. Fragments were added with Android Honeycomb. So if you are developing an application only for Android 3.0 (HoneyComb) or higher then Android provides you access to the Fragments class. You can also access the FragmentManager by calling the getFragmnetManager() method in your Activities. 
 
Create Fragments   
 
For creating Fragments your class needs to extend the Fragment class. The Fragment class has methods, just the same as that of an Activity, like onStart(), onPause, onResume() and onCreate(). Usually you should use onCreateVIew(), onCreate() and onStop() methods in your class.
 
onCreateView()
 
The system calls this method when Android needs the layout for the fragment.
 
Modify Fragment at run time
 
The Fragment class and Fragment Transaction class allow you to add, remove and replace fragments in the layout of your activity. Fragments can be dynamically modified by the transaction. To dynamically add fragments to an existing layout you typically define a container in the XML layout file in which you add a fragment. For this you can use a framelayout as in the following:
  1. FragmentManager fm = getFragmentManager();  
  2. FragmentTransaction fragmentTransaction = fm.beginTransaction();  
  3. Fragment1 fm2 = new Fragment1();  
  4. fragmentTransaction.add(R.id.fragment_container, fm2, "HELLO");  
  5. fragmentTransaction.commit();   
Step 1
 
Create a project like this:
 
Clipboard04.jpg
 
Step 2
 
Create an XML file and write the following. 
 
In this you will use a Button inside a LinearLayout that when clicked will load the fragment.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:layout_width="fill_parent"  
  4.               android:layout_height="fill_parent"  
  5.               android:orientation="vertical" >  
  6.    
  7.     <Button  
  8.             android:id="@+id/loadbutton"  
  9.             android:layout_width="fill_parent"  
  10.             android:layout_height="wrap_content"  
  11.             android:text="ButtonLoad"  
  12.             />  
  13.    
  14.     <LinearLayout  
  15.             android:id="@+id/fragment1"  
  16.             android:layout_width="fill_parent"  
  17.             android:layout_height="wrap_content"  
  18.             android:orientation="vertical"  
  19.             >  
  20.     </LinearLayout>  
  21. </LinearLayout> 
Step 3
 
Create an XML file and write the following.
 
In this you will use a TextView.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.               android:layout_width="match_parent"  
  4.               android:layout_height="match_parent"  
  5.               android:orientation="vertical" >  
  6.    
  7.     <TextView  
  8.             android:layout_width="wrap_content"  
  9.             android:layout_height="wrap_content"  
  10.             android:layout_gravity="center_horizontal"  
  11.             android:text="Frament1"  
  12.             />  
  13.    
  14. </LinearLayout> 
Step 4
 
Create a Java file and write the following.
 
In this Java class file you will first use the id of the button and set the VIew on its clickListener. In its onclick() event you will get the fragmentManager by calling the getFragmentManager() method and Fragment Transaction by calling the beginTransaction method. And finally, you will commit the transaction.   
  1. import android.annotation.TargetApi;  
  2. import android.app.FragmentManager;  
  3. import android.app.FragmentTransaction;  
  4. import android.os.Build;  
  5. import android.os.Bundle;  
  6. import android.app.Activity;  
  7. import android.view.Menu;  
  8. import android.view.View;  
  9. import android.widget.Button;  
  10.    
  11. public class MainActivity extends Activity {  
  12.    
  13.     /** Called when the activity is first created. */  
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity_main);  
  18.    
  19.         Button button = (Button) findViewById(R.id.loadbutton);  
  20.    
  21.         View.OnClickListener viewlistener = new View.OnClickListener() {  
  22.    
  23.             @TargetApi(Build.VERSION_CODES.HONEYCOMB)  
  24.             @Override  
  25.             public void onClick(View v) {  
  26.                 FragmentManager fm = getFragmentManager();  
  27.                 FragmentTransaction fragmentTransaction = fm.beginTransaction();  
  28.                 Fragment1 fm2 = new Fragment1();  
  29.                 fragmentTransaction.add(R.id.fragment_container, fm2, "HELLO");  
  30.                 fragmentTransaction.commit();  
  31.             }  
  32.         };  
  33.    
  34.         button.setOnClickListener(viewlistener);  
  35.    
  36.     }  

Step 5
 
Create another class file and write this:
  1. package com.myfragments;  
  2. import android.annotation.TargetApi;  
  3. import android.app.Fragment;  
  4. import android.os.Build;  
  5. import android.os.Bundle;  
  6. import android.view.LayoutInflater;  
  7. import android.view.View;  
  8. import android.view.ViewGroup;  
  9.    
  10. @TargetApi(Build.VERSION_CODES.HONEYCOMB)  
  11. public class Fragment1 extends Fragment {  
  12.     @Override  
  13.     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {  
  14.         /** Inflating the layout for this fragment **/  
  15.         View v = inflater.inflate(R.layout.fragment1, null);  
  16.         return v;  
  17.     }  

Step 6
 
When you run the application:
 
Clipboard02.jpg
 
When you click on the button:
 
Clipboard03.jpg


Similar Articles