Listing your fragment back stack with Android’s navigation component
Dec 19, 2022
Just a heads up for anyone using the Android’s navigation component that fragment back stack management differs from the “classic” approach.
Unfortunately, this approach is not helpful when it comes to listing your fragment backstack. What should be done instead is this:
fun Fragment.listFragments(tag: String) {
val fm = (requireParentFragment() as NavHostFragment).childFragmentManager
fm.fragments.forEachIndexed { index, fragment ->
Log.d(tag, "Fragment $index: ${fragment.javaClass.simpleName}")
}
}
Considering, of course, that you’re using Androidx fragments.
The thing is that all of the backstack data is now contained within the NavHostFragment so you have to use the code above to properly list all of your fragments in the backstack.