Android Fragments BackStack Tutorial With Example Programmatically

android fragments kotlin backstack

Hello, all. Welcome to Android Fragments 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.

Download Source Code For Android Fragments Example

[sociallocker] Download BasicFragmentBackStackDemonuts [/sociallocker]

Step 1: Create a new project in Android Studio.

Make a new project in android studio. Consider a main activity as empty activity.

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.

Kotlin Version

Kotlin version of this tutorial is available here: Android Fragment Kotlin Backstack tutorial.

So that is all for Fragments Android example.

Feel free to comment your queries and reviews in the comment section. Thank you.