如何解决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)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。