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

3

58

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.

Schoof answered 18/8, 2012 at 2:36 Comment(0)
E
112

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());
}
Extrados answered 18/8, 2012 at 4:24 Comment(2)
getId returns the id of backstack not the fragmentSusy
Downvote because this is wrong. If you execute findFragmentById() and use these ids, you will not find a fragment.Leitmotiv
R
0

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.

Ransome answered 8/11, 2023 at 14:47 Comment(2)
Hi backQueue doesn't exist ?Kremenchug
backQueue is private and you can not access it.Parada
G
-2

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.

Gendron answered 13/3, 2017 at 10:42 Comment(2)
How is this an answer to the question asked?Hypochondriac
This doesn't seem to be related to the question asked.Eelpout

© 2022 - 2024 — McMap. All rights reserved.