Lucas P.
Lucas P.

Reputation: 4532

Navigation Component: Find if a fragment is in the back stack

I'm trying to find if a fragment is already in the backStack of my NavHostFragment (so it automatically manages the fragment transactions and backstack), in order to pop back to it when the user selects that destination from my Side Menu, instead of adding another new fragment to the backstack.

Here's the catch: Many of my fragments are the same Class, let's call it ArticleListFragment, and their contentId param (a simple string id) changes what is being displayed in those fragments.

This means I cannot use nav_host_fragment.childFragmentManager.findFragmentById() since multiple of my fragments in the backstack have the same fragment id.

What I've tried so far is this

var foundIndex = -1
for (i in 0 until nav_host_fragment.childFragmentManager.backStackEntryCount) {
    val currFragmentTag = nav_host_fragment.childFragmentManager.getBackStackEntryAt(i).name
    val currFragmentId = nav_host_fragment.childFragmentManager.getBackStackEntryAt(i).id
    //val currFragment = nav_host_fragment.childFragmentManager.findFragmentByTag(currFragmentTag) // always returns null
    val currFragment = nav_host_fragment.childFragmentManager.findFragmentById(currFragmentId) // always returns null 

    // currentFragment is null so the check always fails       
    if (currFragment is ArticleListFragment && currFragment.contentId == "a value I need to check") {
        foundIndex = i
        break
    }
}

Am I doing something wrong? Is there another way to check if a fragment, added by the Android Navigation Component, is already in the back stack?

Upvotes: 1

Views: 2035

Answers (1)

Mustafa Ozhan
Mustafa Ozhan

Reputation: 351

Well, I had the same issue, i can not say that this is a perfect solution but you can get it with

findNavController()
.backStack
.firstOrNull { it.destination.id == ID_YOU_WANT_TO_CHECK }

backstack is actually restricted so the method needs to be Suppressed.

@SuppressLint("RestrictedApi")

Upvotes: 5

Related Questions