How to get a list of backstack fragment entries in android?

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: Grouped notifications and summary still shown separately on 4.4 and below
  • <size> attribute not useful when using layer-list?
  • Write enum with String to parcel
  • ImageView that is a fixed size, regardless of image size
  • Android Studio: can't edit files after a while
  • Difference between declare-styleable and style
  • Related posts:

    Updating the list view when the adapter data changes
    Is there a programmatic way to detect if the camera has an optical zoom?
    Redirect traffic of Google Talk for Android
    Android: How can I validate EditText input?
    Could not find adb.exe - after upgrade to Android SDK 2.3
    Android - Storing/retrieving strings with shared preferences
  • Black screen before Splash screen appear in android
  • Game engine for iPhone/Android
  • How to enable mDNS support in android browser address bar
  • SpannableString with Image example
  • What is a “slider interrupt” on Android
  • how to create a new AVD in eclipse?
  • 2 Solutions collect form web for “How to get a list of backstack fragment entries in 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());
    }
    

    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.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.