How to get a list of backstack fragment entries in android?
AndroidTabsAndroid FragmentsBack StackAndroid Problem Overview
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.
Android Solutions
Solution 1 - Android
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());
}
Solution 2 - Android
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.