[英]Navigation component , check if fragment exists in back stack
使用導航組件時如何檢查返回堆棧中是否存在片段?
我能想到的一件事是嘗試通過使用獲取NavBackStackEntry
val backStackEntry=findNavController().getBackStackEntry(R.id.courseTrackFeedbackFragment)
在文檔中它說如果目標不在返回堆棧上,這將拋出 IllegalArgumentException。 但這看起來像 hack,有更好的方法嗎?
是的,這似乎是今天唯一的方法
try {
getBackStackEntry(resId)
} catch (ignored: Throwable) {
}
一個簡單的擴展 function:
fun NavController.isFragmentRemovedFromBackStack(destinationId: Int) =
try {
getBackStackEntry(destinationId)
false
} catch (e: Exception) {
true
}
好像沒有別的辦法了,這些是我目前正在使用的擴展
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)
}
要檢查堆棧中是否存在任何片段,或者片段是否是第一個片段,我正在使用這個 function:
if (findNavController(R.id.nav_host).previousBackStackEntry?.id != null)
//Fragment exists in back stack
else
//No fragment exists in back stack
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.