Manohar
Manohar

Reputation: 23404

Navigation component , check if fragment exists in back stack

How can I check if a fragment exists in back stack when using navigation component ?

one thing I can think of is try to get the NavBackStackEntry by using

val backStackEntry=findNavController().getBackStackEntry(R.id.courseTrackFeedbackFragment)

In documentation it says this will throw IllegalArgumentException if the destination is not on the back stack . But this looks like a hack , is there a better way to do it ?

Upvotes: 10

Views: 4940

Answers (4)

Binish Manandhar
Binish Manandhar

Reputation: 21

To check if any fragment exists on stack or if the fragment is first I'm using this function:

if (findNavController(R.id.nav_host).previousBackStackEntry?.id != null)
  //Fragment exists in back stack
else
  //No fragment exists in back stack

Upvotes: 1

Manohar
Manohar

Reputation: 23404

Seems like there is no other way , these are the Extensions I am using currently

fun NavController.isFragmentInBackStack(destinationId: Int) =
    try {
        getBackStackEntry(destinationId)
        true
    } catch (e: Exception) {
        false
    }

and

fun Fragment.isFragmentInBackStack(destinationId: Int) =
    try {
        findNavController().getBackStackEntry(destinationId)
        true
    } catch (e: Exception) {
        false
    }

Usage

if (isFragmentInBackStack(R.id.myFragment)){
         findNavController().popBackStack(R.id.myFragment,false)
} else {
         val action = MyCurrentFragmentDirections.actionToMyFragment()
         findNavController().navigateSafe(action)
   }

Upvotes: 13

Aydinozkan
Aydinozkan

Reputation: 2648

A simple extension function:

fun NavController.isFragmentRemovedFromBackStack(destinationId: Int) =
    try {
        getBackStackEntry(destinationId)

        false
    } catch (e: Exception) {
        true
    }

Upvotes: 1

Vlad
Vlad

Reputation: 8572

Yes, it seems to be the only way for today

try {
   getBackStackEntry(resId)
} catch (ignored: Throwable) {
}

Upvotes: 0

Related Questions