首页 > 解决方案 > 导航组件,检查返回堆栈中是否存在片段

问题描述

使用导航组件时如何检查后堆栈中是否存在片段?

我能想到的一件事是尝试 NavBackStackEntry通过使用

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

在文档中它说如果目标不在后堆栈上,这将抛出 IllegalArgumentException 。但这看起来像一个黑客,有没有更好的方法呢?

标签: androidandroid-jetpackandroid-architecture-navigation

解决方案


好像没有别的办法了,这些是我目前正在使用的扩展

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)
   }

推荐阅读