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?
Yes, it seems to be the only way for today
try {
getBackStackEntry(resId)
} catch (ignored: Throwable) {
}
A simple extension function:
fun NavController.isFragmentRemovedFromBackStack(destinationId: Int) =
try {
getBackStackEntry(destinationId)
false
} catch (e: Exception) {
true
}
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)
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.