Reputation: 5850
I'm working on an application in which tabs are implemented using FragmentActivity
. Since, tabs are required throughout the application, fragments are used extensively to make the application compatible on all the versions of android.
As a consequence, I'm facing a problem in visualizing as to what fragments are present on the backstack. I'm sure there is a way to retrieve the list of fragments present on the backstack. Thanks.
Upvotes: 58
Views: 59648
Reputation: 165
I have achieved logging of fragments in the back stack with this code (in Kotlin):
findNavController().backQueue.forEach {
Log.d(TAG, "${it.destination}")
}
This code iterates through every entry in the navigation back stack, printing out the destination name of the Fragment.
Upvotes: 0
Reputation: 7315
The FragmentManager has methods:
getBackStackEntryCount()
getBackStackEntryAt (int index)
FragmentManager fm = getFragmentManager();
for(int entry = 0; entry<fm.getBackStackEntryCount(); entry++){
Log.i(TAG, "Found fragment: " + fm.getBackStackEntryAt(entry).getId());
}
Upvotes: 112
Reputation: 459
If you want to check which fragment is visible and if you know the id of view where fragment is placed, first you have to add below in onCreate()
getSupportFragmentManager().addOnBackStackChangedListener(new OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame);
if (f != null){
updateActionBarTitle(f);
}
}
});
private void updateActionBarTitle(Fragment fragment) {
String fragClassName = fragment.getClass().getName();
if (fragClassName.equals(FirstFragment.class.getName())) {
setTitle("Home");
} else if (fragClassName.equals(SecondFragment.class.getName())) {
setTitle("Second");
}
}
This will update your action bar title on back stack change listener.
Upvotes: -2