Close
Close full mode
logoAppDevAssist

Introduction to backstack in fragments

Last update: 2 months ago by n-k-dReading time: 2 min

Introduction to backstack:

This post will give you an introduction to fragment backstack and how to put one fragment in a backstack and how to remove it from the backstack.

Video:

I have published one video on YouTube that explains it in step by step. You can watch it here:

Methods used with backstack:

Below methods are used while we are interacting with backstack:

addOnBackStackChangeListener:

This method is used to add one listener that notifies on any change in backstack.

getBackStackEntryAt(int index):

Get the back stack value for a given index.

getBackStackEntryCount():

Get the total count of a backstack.

popBackStack():

popBackStack(String name, int flags):

popBackStack(int id, int flags):

Pop a transaction from a backstack.

How to add a listener to backstack:

We can add one backstack change listener and print all back stack entries as like below:

fragmentManager.addOnBackStackChangedListener {
for (i in 0 until fragmentManager.backStackEntryCount){
Log.d("MainActivity", fragmentManager.getBackStackEntryAt(i).name.toString());
}
}

And, we can add one fragment transaction to a backstack as like below:

val fragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.add(R.id.frameLayout, FirstFragment())
fragmentTransaction.addToBackStack("FirstFragment - ${count++}")
fragmentTransaction.commit()

count is a variable that changes if we are adding a fragment. It will keep the name unique.

If we add any fragment transaction to a backstack, the listener will show all entries.

Remove one transaction from backstack:

popBackstack is used to remove the last inserted transaction from the backstack. We can use it as like below:

fragmentManager.popBackStack()

We can also pass the name of the transaction and upto that transaction, all other transactions will be removed.

fragmentManager.popBackStack(name, flags)

flags can be 0 or 1. If 0 it will not remove the transaction whose name is given. It will be removed only if we provide any other value like 1.

The YouTube video shows these steps with an example.

Subscribe to our Newsletter

Previous
How to add fragments dynamically in Android(Kotlin)
Next
How to handle user interactions in Fragments