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)