android - 导航组件,检查返回堆栈中是否存在片段
问题描述
使用导航组件时如何检查后堆栈中是否存在片段?
我能想到的一件事是尝试 NavBackStackEntry
通过使用
val backStackEntry=findNavController().getBackStackEntry(R.id.courseTrackFeedbackFragment)
在文档中它说如果目标不在后堆栈上,这将抛出 IllegalArgumentException 。但这看起来像一个黑客,有没有更好的方法呢?
解决方案
好像没有别的办法了,这些是我目前正在使用的扩展
fun NavController.isFragmentInBackStack(destinationId: Int) =
try {
getBackStackEntry(destinationId)
true
} catch (e: Exception) {
false
}
和
fun Fragment.isFragmentInBackStack(destinationId: Int) =
try {
findNavController().getBackStackEntry(destinationId)
true
} catch (e: Exception) {
false
}
用法
if (isFragmentInBackStack(R.id.myFragment)){
findNavController().popBackStack(R.id.myFragment,false)
} else {
val action = MyCurrentFragmentDirections.actionToMyFragment()
findNavController().navigateSafe(action)
}