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() {
@Override
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.

Author: androidsmartly

I am a Tech Enthusiast who likes to work on new Ideas. Sharing knowledge on Android, Marketing, Startups and More.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s