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 interfacepurposes. 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 Activites. 

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:

  FragmentManager fm = getFragmentManager();
  FragmentTransaction fragmentTransaction = fm.beginTransaction();
  Fragment1 fm2 = new Fragment1();
  fragmentTransaction.add(R.id.fragment_container, fm2, "HELLO");
  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.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

              android:layout_width="fill_parent"

              android:layout_height="fill_parent"

              android:orientation="vertical" >

 

    <Button

            android:id="@+id/loadbutton"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:text="ButtonLoad"

            />

 

    <LinearLayout

            android:id="@+id/fragment1"

            android:layout_width="fill_parent"

            android:layout_height="wrap_content"

            android:orientation="vertical"

            >

    </LinearLayout>

</LinearLayout>



Step 3

Create an XML file and write the following.

In this you will use a TextView.

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

              android:layout_width="match_parent"

              android:layout_height="match_parent"

              android:orientation="vertical" >

 

    <TextView

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_gravity="center_horizontal"

            android:text="Frament1"

            />

 

</LinearLayout>

Step 4

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

 

import android.annotation.TargetApi;

import android.app.FragmentManager;

import android.app.FragmentTransaction;

import android.os.Build;

import android.os.Bundle;

import android.app.Activity;

import android.view.Menu;

import android.view.View;

import android.widget.Button;

 

public class MainActivity extends Activity {

 

    /** Called when the activity is first created. */

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        Button button = (Button) findViewById(R.id.loadbutton);

 

        View.OnClickListener viewlistener = new View.OnClickListener() {

 

            @TargetApi(Build.VERSION_CODES.HONEYCOMB)

            @Override

            public void onClick(View v) {

                FragmentManager fm = getFragmentManager();

                FragmentTransaction fragmentTransaction = fm.beginTransaction();

                Fragment1 fm2 = new Fragment1();

                fragmentTransaction.add(R.id.fragment_container, fm2, "HELLO");

                fragmentTransaction.commit();

            }

        };

 

        button.setOnClickListener(viewlistener);

 

    }

}

Step 5

Create another class file and write this:

package com.myfragments;

import android.annotation.TargetApi;

import android.app.Fragment;

import android.os.Build;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

 

@TargetApi(Build.VERSION_CODES.HONEYCOMB)

public class Fragment1 extends Fragment {

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        /** Inflating the layout for this fragment **/

        View v = inflater.inflate(R.layout.fragment1, null);

        return v;

    }

}


Step 6

When you run the application:

Clipboard02.jpg

When you click on the button:

Clipboard03.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all