Android Fragment Tutorial | Fragment Backstack Lifecycle Example

android gridview, android fragment tutorial, android scrollview, android horizontal scrollview, android fillviewport, android spinner

Android Fragment Tutorial With Example For Beginners is the today’s leading topic.

In this article, I will cover about the fragment implementation and it’s usage.

Below are the direct links to the examples.

1. Android Fragment Example For Beginners

2. Android Fragment With TextView and Button

3. Android Fragment Backstack Lifecycle Example

You may have noticed one thing while using the android app of WhatsApp that they have slider tabs on the main page.

Mainly, there are three parts in the main screen of WhatsApp, Chats, Status and Call. When you slide horizontally among these three tabs, every tab have different layout but they are not opening in new activity.

Instead, all three are changing inside specific and static rectangle place only. Here, they have used fragments for layout of these three tabs.

Fragment Basic Information

Fragment is one kind of sub-activity which actually runs in the activity itself.

Similar to activity, fragment have both XML file for layout designing and a JAVA class for logical purpose.

Fragment is a modular section of any activity which has its own lifecycle, receives its own input events, and which you can add or remove while the activity is running (sort of like a “sub activity” that you can reuse in different activities).

To build a multi pane User Interface, you can combine multiple fragments in a single activity.

You can also make reuse fragments in more than one activity.

A fragment must be hosted by any activity. Every fragment’s lifecycle is directly affected by it’s parent activity’s lifecycle.

For example, when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all fragments.

However, you change the state of any fragment (such as add or remove) when the activity is in running mode.

Android also provides the feature to add the fragment to the backstack similar to that the backstack of activity.

When you add a fragment as a part of your activity layout, it lives in a ViewGroup inside the activity’s view hierarchy and the fragment defines its own view layout.

Design Pattern For Fragment

Android introduced fragments in Android 3.0 (API level 11 – honeycomb).

Main aim for this is to support more dynamic and flexible UI designs on large screens, such as tablets.

In the larger screen of the tablet, there is much more space to combine and interchange the UI components effectively.

This is where fragments help us to create such type of designs without handling the complex view hierarchy.

When you divide the activity’s layout into various components using fragments, you are able to change the activity’s look and feel at the runtime.

To understand the fragment easily let us take the example of an news application.

Here, at the left sidebar we can use one fragment to show the list of an articles.

At the right side, another fragment will show whole article in depth. These both fragments are in the same activity.

Take a look at the below image (Image credit goes here)

android fragment tutorial
Two fragments in single Activity

Now for the same application, consider the screen of mobile device. It is relatively small compare to the tablet.

So in this case, we can create two activities. First activity will hold the first fragments with the lists of the articles.

When the user clicks on any article from the list, we will open another activity with second fragment which will show up the whole article.

Here, we have created both the fragment such that we can use them with single activity as well as with separate activities. Hence, fragments have demonstrated the re usability feature.

So now we can summarize that a fragment is a kind of sub-activity that enable us to creat emulti pane User Interface for activity.

We can use fragment when we want to have an activity which changes the user interface of the specific limited place on the screen with user input.

After this much information, you have enough basic idea about the importance of the fragment in android app development.

Now let us create practical examples with android studio to see how the theory of fragment actually works in android app.

Fragments Examples In Android Studio

Let us create two fragments example in android studio to see the practical execution of fragments.

First example will contain simple and basic fragment implementations.





1. Android Fragment Example For Beginners

In this example, we will create a fixed space into the area of activity. In this fixed space, we will show up two fragments one by one.

Meaning is that, one fragment will fill entire space when we click on the first button from activity.

When we click the second button from activity, second fragment will entirely replace the first fragment.

Step 1. Layout Writings

In the activity_main.xml file, add the below source code

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        android:id="@+id/fr1"
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#fff"
        android:background="#e11010"
        android:textStyle="bold"
        android:text="Fragment 1" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:id="@+id/fr2"
        android:layout_margin="10dp"
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#fff"
        android:background="#1010e1"
        android:textStyle="bold"
        android:text="Fragment 2"/>

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/frame_container"
        android:layout_margin="15dp">


    </FrameLayout>

</LinearLayout>

I have added two textview and framelayout in the above XML file.

FrameLayout will hold the specific place in which we will create our fragment.

In short, design and UI widget of the fragment will be visible in the framelayout.

On the click event of both textviews, we will make different fragments.

Step 2. Making Fragments

Make a new fragment and give it a name FragmentOne.

Compiler will create two files : fragment_fragment_one.xml and FragmentOne.java 

Add the following source code in fragment_fragment_one.xml file

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".FragmentOne">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textStyle="bold"
        android:textSize="30sp"
        android:gravity="center"
        android:textColor="#fff"
        android:background="#e70ba5"
        android:text="I am Fragment 1" />

</FrameLayout>

I have taken one textview in this file.

Parent tag of this file is the framelayout.

In the FragmentOne.java file, write down the following lines

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class FragmentOne extends Fragment {

    public FragmentOne() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_one, container, false);
    }

}

Using this file, you can control the UI widget of this fragment.

In onCreateView() method, compiler will inflate the fragment_fragment_one.xml file. Thus, it will get the view of  fragment_fragment_one.xml file.

Now prepare another fragment and give it a name FragmentTwo.

Two files for this fragment are fragment_fragment_two.xml and FragmentTwo.java

Source code for fragment_fragment_two.xml looks like the below

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".FragmentTwo">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textStyle="bold"
        android:textSize="30sp"
        android:gravity="center"
        android:textColor="#fff"
        android:background="#e7880b"
        android:text="I am Fragment 2" />

</FrameLayout>

Same as the fragment_fragment_one.xml file, it also has one textview.

FragmentTwo.java should have the below coding lines

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;


public class FragmentTwo extends Fragment {


    public FragmentTwo() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_fragment_two, container, false);
    }

}

This file will inflate fragment_fragment_two.xml to create the look and feel of the second fragment.

Step 3. Last Change

Finally, change the source code for MainActivity.java as per the below one

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private TextView tv1, tv2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv1 = findViewById(R.id.fr1);
        tv2 = findViewById(R.id.fr2);

        tv1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new FragmentOne(),false,"one");
            }
        });

        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new FragmentTwo(),false,"two");
            }
        });

    }

    public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        if (addToBackStack) {
            ft.addToBackStack(tag);
        }
        ft.replace(R.id.frame_container, fragment, tag);
        ft.commitAllowingStateLoss();
    }

}

As we have seen in the activity_main.xml file, there are two textviews in the main file.

Click events of these textviews are written in this file.

On the click of first textview, compiler will open the first fragment. (FragmentOne.java)

Another textview will open the second fragment. (FragmentTwo.java)

Compiler is using the addFragment() method to open a new fragment.

Code structure for addFragment() method is as the following

 public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        if (addToBackStack) {
            ft.addToBackStack(tag);
        }
        ft.replace(R.id.frame_container, fragment, tag);
        ft.commitAllowingStateLoss();
    }

This method has three parameters.

First one is the name of the fragment which we want to open in the framelayout.

Second one is the boolean. If it’s value is true then compiler will add this fragment to the backstack.

If the value is false, then it won’t add the fragment in backstack.

Last one is the tag in the string format which acts as a identifier for the fragment.

This method will use FragmentManager and FragmentTransaction class to create a fragment.

Below video demonstrate the final output of the above fragment example





This example is about the demonstration about controlling the UI widgets of the fragments.

2. Android Fragment With TextView and Button

In this example, I will show you how to control the UI widgets like textview, button, Imageview etc. in the fragment’s java class.

We will create only one fragment in this example.

Inside this fragment, we will add one textview and two buttons.

When the user clicks the button, we change the value of the textview. Click event of both button will fill different text in the textview.

Prepare a new project in the android studio.

Select empty activity as a default activity to have pure clean project.

Step 1. Layout of Main

Your code for activity_main.xml file is as the below

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

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_margin="10dp"
        android:id="@+id/fr1"
        android:gravity="center"
        android:textSize="20dp"
        android:textColor="#fff"
        android:background="#e11010"
        android:textStyle="bold"
        android:text="I am in Activity" />


    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/frame_container"
        android:layout_margin="15dp">


    </FrameLayout>

</LinearLayout>

This file has one textview and one framelayout.

Similar to above example, framelayout will hold the fragment.

While textview says that it is placed in the layout of activity so that we can differentiate the area of activity with the area of fragment.

Step 2. Blank Fragment

Create a new fragment and name it a Blank Fragment.

In the fragment_blank.xml file, add the below code structure.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
    tools:context=".BlankFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="#67e99f"
        android:orientation="vertical">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:layout_margin="10dp"
            android:id="@+id/tv"
            android:gravity="center"
            android:textSize="20dp"
            android:textColor="#ffffff"
            android:background="#10a6e1"
            android:textStyle="bold"
            android:text="Me and two buttons are in Fragment" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 1"
            android:id="@+id/btn1"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button 2"
            android:id="@+id/btn2"/>

    </LinearLayout>

</FrameLayout>

One textview and two buttons are there in the above layout file.

We will change the value of the textview on the click event of both the buttons.

Now in the BlankFragment.java file, write down the following code block

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;


public class BlankFragment extends Fragment {

    private Button btn1, btn2;
    private TextView textView;
    private View view;

    public BlankFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        view = inflater.inflate(R.layout.fragment_blank, container, false);

        textView = view.findViewById(R.id.tv);
        btn1 = view.findViewById(R.id.btn1);
        btn2 = view.findViewById(R.id.btn2);

        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("You Clicked Button 1");
            }
        });

        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("You Clicked Button 2");
            }
        });

        return view;
    }

}

In this file, I have written the code for the click event of both the buttons.

When the user clicks on the first button, Compiler will set the value of the textview as like “You clicked Button 1”

Similarly, on the click event of second button, a toast will pop up like “You clicked Button 2”.

Thus, you can see that we have learn how to control the click event and to change the value of textview from the JAVA file of the fragment.

Similarly, you can change the value of imageview, button text etc. from this JAVA class.

Step 3. Main JAVA file

Now in the MainActivity.java file, add the following source code

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        addFragment(new BlankFragment(),false,"two");

    }

    public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        if (addToBackStack) {
            ft.addToBackStack(tag);
        }
        ft.replace(R.id.frame_container, fragment, tag);
        ft.commitAllowingStateLoss();
    }

}

In this class, we will simply add the fragment in the container.





3. Android Fragment Backstack Lifecycle Example

Hello, all. Welcome to Android Fragments Backstack lifecycle tutorial for beginners.

In Android fragments example, you will learn how to create a basic fragment with a simple example and source code.

You will learn how to create maintain multiple fragments in one activity.

We will see how to handle and manage backstack of fragments.

Android Studio will be used to make android fragments tutorial with example.

First, check the output of Android fragments example, then we will develop it.

Step 2: Creating Two Fragments

Make two new fragments and give them name as “OneFragment” and “TwoFragment.”

Add below code in OneFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class OneFragment extends Fragment {

    public OneFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_one, container, false);
    }
}

Paste following source code in fragment_one.xml

<FrameLayout 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="@color/colorAccent"
    tools:context="com.exampledemo.parsaniahardik.basicfragmentbackstackdemonuts.OneFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="25sp"
        android:gravity="center"
        android:textColor="#fff"
        android:text="Fragment One" />

</FrameLayout>

Add below code in TwoFragment.java

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class TwoFragment extends Fragment {

    public TwoFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_two, container, false);
    }
}

Copy following in fragment_two.xml

<FrameLayout 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="@color/colorPrimary"
    tools:context="com.exampledemo.parsaniahardik.basicfragmentbackstackdemonuts.OneFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="25sp"
        android:gravity="center"
        android:textColor="#fff"
        android:text="Fragment Two" />

</FrameLayout>

Step 3: Making BackStack Activity

Create a new activity named “BackStackActivity.”

Copy following in activity_back_stack.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:orientation="vertical"
    tools:context="com.exampledemo.parsaniahardik.basicfragmentbackstackdemonuts.BackStackActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/btnfr1with"
            android:layout_height="wrap_content"
            android:text="Frag. 1 with backstack" />
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/btnfr2with"
            android:layout_height="wrap_content"
            android:text="Frag. 2 with backstack" />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container_frame_back"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">


    </LinearLayout>

</LinearLayout>

Add below in BackStackActivity.java

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class BackStackActivity extends AppCompatActivity {

    private Button btnFrag1WithBack,btnFrag2WithBack;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_back_stack);

        btnFrag1WithBack = (Button) findViewById(R.id.btnfr1with);
        btnFrag2WithBack = (Button) findViewById(R.id.btnfr2with);

        btnFrag1WithBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new OneFragment(),true,"one1");
            }
        });

        btnFrag2WithBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new TwoFragment(),true,"two2");
            }
        });
    }

    public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        if (addToBackStack) {
            ft.addToBackStack(tag);
        }
        ft.replace(R.id.container_frame_back, fragment, tag);
        ft.commitAllowingStateLoss();
    }
}

Step 4: Description of BackStackActivity

Below method is used to create a fragment.

 public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        if (addToBackStack) {
            ft.addToBackStack(tag);
        }
        ft.replace(R.id.container_frame_back, fragment, tag);
        ft.commitAllowingStateLoss();
}

In the second parameter, a boolean variable “addToBackStack” is passed.

If addToBackStack is true then, the fragment will be saved in back stack. That means when a user clicks on the back button all the fragments present in backstack will be set in container_frame as per its order.

Step 5: Updating MainActivity

Add below to activity_main.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:orientation="vertical"
    tools:context="com.exampledemo.parsaniahardik.basicfragmentbackstackdemonuts.MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/btnfr1without"
            android:layout_height="wrap_content"
            android:text="Frag. 1 without backstack" />
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:id="@+id/btnfr2without"
            android:layout_height="wrap_content"
            android:text="Frag. 2 without backstack" />

    </LinearLayout>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/btnback"
        android:text="fragment with backstack"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/container_frame"
        android:layout_marginTop="5dp"
        android:orientation="horizontal">


    </LinearLayout>

</LinearLayout>

Add following in MainActivity.java

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    private Button btnFrag1WithoutBack, btnFrag2WithoutBack, btnback;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnFrag1WithoutBack = (Button) findViewById(R.id.btnfr1without);
        btnFrag2WithoutBack = (Button) findViewById(R.id.btnfr2without);
        btnback = (Button) findViewById(R.id.btnback);

        btnback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,BackStackActivity.class);
                startActivity(intent);
            }
        });

        btnFrag1WithoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new OneFragment(), false, "one");
            }
        });

        btnFrag2WithoutBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFragment(new TwoFragment(), false, "two");
            }
        });

    }

    public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        if (addToBackStack) {
            ft.addToBackStack(tag);
        }
        ft.replace(R.id.container_frame, fragment, tag);
        ft.commitAllowingStateLoss();
    }

}

Step 6: Description of MainActivity

Following method is used to open fragment.

 public void addFragment(Fragment fragment, boolean addToBackStack, String tag) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        if (addToBackStack) {
            ft.addToBackStack(tag);
        }
        ft.replace(R.id.container_frame, fragment, tag);
        ft.commitAllowingStateLoss();
}

Same as in BackStackActivity, a boolean addToBackStack  variable is passed in the second parameter.

Here it is false, so if a user clicks back button, the app will be closed because nothing was saved in the backstack.

So that is all for Fragments Android example.