Android Fragments BackStack Tutorial With Example Programmatically

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

Paste following source code in fragment_one.xml

Add below code in TwoFragment.java

Copy following in fragment_two.xml

Step 3: Making BackStack Activity

Create a new activity named “BackStackActivity.”

Copy following in activity_back_stack.xml

Add below in BackStackActivity.java

Step 4: Description of BackStackActivity

Below method is used to create a fragment.

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

Add following in MainActivity.java

Step 6: Description of MainActivity

Following method is used to open fragment.

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.

Hardik Parsania

I am mobile app developer. I am always passionate about solving complex and real world problems.I have developed many apps with great interest and superior logical skills.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *