Listing your fragment back stack with Android’s navigation component

--

Photo by Eaters Collective on Unsplash

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.

--

--

Nikolay Miroshnychenko
Nikolay Miroshnychenko

Written by Nikolay Miroshnychenko

Android engineer. Learning daily and sharing my knowledge in the process. Into mobile, computer science, and the brain.

No responses yet