navController.currentDestination + findFragmentById返回null

问题描述

由于我使用的是导航组件而不是片段管理器,因此我试图找到导航到使用navController的最后一个片段的ID:

override fun onBackPressed() {
    val fragment = this.supportFragmentManager.findFragmentById(navController.currentDestination!!.id)
    (fragment as IOnBackPressed).onBackPressed().not().let {
        if (it) super.onBackPressed()
    }
}

但是,触发此代码时,我不断收到以下错误消息:

kotlin.TypeCastException: null cannot be cast to non-null type com.google.apps.sanctified.IOnBackPressed
    at com.google.apps.sanctified.SanctifiedActivity.onBackPressed(SanctifiedActivity.kt:41)

我在调试器中浏览了代码,看来navController在其后堆栈中找到了正确的目的地并返回了正确的ID。但是,findFragmentById()似乎没有该片段的任何记录,并且始终返回null。该文档说该功能:

找到一个片段,该片段在从XML扩展时被给定的id标识,或者在添加到事务中时被查找为容器ID。

很明显,我没有使用交易,但是应该在通货膨胀时进行更新。也许我在那儿做错了事:

override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
    binding = DetailFragmentBinding.inflate(inflater,container,false)
    return binding.root
}

解决方法

需要使用此:

navHost.childFragmentManager.findFragmentById(R.id.nav_host)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...