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.