'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 ?
Solution 1:[1]
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)
}
Solution 2:[2]
Yes, it seems to be the only way for today
try {
getBackStackEntry(resId)
} catch (ignored: Throwable) {
}
Solution 3:[3]
A simple extension function:
fun NavController.isFragmentRemovedFromBackStack(destinationId: Int) =
try {
getBackStackEntry(destinationId)
false
} catch (e: Exception) {
true
}
Solution 4:[4]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Manohar |
| Solution 2 | Vlad |
| Solution 3 | Aydinozkan |
| Solution 4 | Binish Manandhar |
