Learn how to use the OnBackStackChangedListener to get the current Fragment

Suppose your App Title changes based on the Fragment name. So if you have three fragments FragmentA, FragmentB and FragmentC then the title will be based on the Fragment being displayed.

Like if you are at FragmentA then the App title will become FragmentA and so on.

Now if you navigate from FragmentA to FragmentB and then click on back button how will you know which Fragment you are at.

To solve this problem you can add a OnBackStackChangedListener.

Let’s see the steps to do this. You can refer to the source code for this illustration here.

1. When you replace a fragment in the code then attach a name to it.

ft.replace(R.id.frameLayoutId, tf, “visible_fragment”);

2. Add a Backstack Listener

getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
Fragment currentBackStackFragment = getFragmentManager().findFragmentByTag(“visible_fragment”);
if(currentBackStackFragment instanceof TopFragment){
//Add Code

This listener will be called when you click on the back button. The logic will help you to identify the Fragment.

So go ahead and try this out.

What is Back Stack and Why it’s Important

When you use an App on your Android Device I am sure you press the back button pretty often. Which in turn takes you to the previous Screen.

This happens because of the Back Stack which maintains a history of places you have visited.

Each visit is a transaction. So the back stack essentially keeps an eye on all the transactions. Using the back stack effectively can lead to to a good user experience.

A transaction can be moving from one Activity to another or from one Fragment to another. So if the user wants to go back to the previous Activity or Fragment
the Back Button will enable that action.

How this concept applies to our App we will discover in the next Article.

Read the Android Documentation to explore this further.