0

如果我尝试从底部工作表对话框片段导航到另一个片段,我的应用程序将崩溃。

我现在在底部工作表对话框片段中执行此操作:

someButton.setOnClickListener { view ->  
   val action = DestinationFragmentDirections.actionCurrentFragmentToDestinationFragment()
   view?.findNavController()?.navigate(action)
}

崩溃日志:

java.lang.IllegalStateException: View androidx.appcompat.widget.AppCompatButton{c44315f VFED..C.. ...P.... 44,1189-1036,1321 #7f0a00ff app:id/fragment_book_details_btn_edit} does not have a NavController set
        at androidx.navigation.Navigation.findNavController(Navigation.java:84)
        at androidx.navigation.ViewKt.findNavController(View.kt:28)
        at com.bose.bosushree.view.book_details.BookDetailsFragment.setClickListeners$lambda-4$lambda-3(BookDetailsFragment.kt:75)
        at com.bose.bosushree.view.book_details.BookDetailsFragment.lambda$OwDld1VFgq8jsjr6EbpPx5MD4aU(Unknown Source:0)
        at com.bose.bosushree.view.book_details.-$$Lambda$BookDetailsFragment$OwDld1VFgq8jsjr6EbpPx5MD4aU.onClick(Unknown Source:2)
        at android.view.View.performClick(View.java:6256)
        at android.view.View$PerformClick.run(View.java:24701)
        at android.os.Handler.handleCallback(Handler.java:789)
        at android.os.Handler.dispatchMessage(Handler.java:98)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6541)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
4

2 回答 2

0

根据Navigate to a Destination 指南,您可以使用findNavController()Fragment 上的扩展来获取NavController. 这适用于任何类型的片段,包括BottomSheetDialogFragment.

someButton.setOnClickListener { view ->  
   val action = DestinationFragmentDirections.actionCurrentFragmentToDestinationFragment()
   findNavController().navigate(action)
}
于 2021-09-13T16:23:58.027 回答
0

因此,对话框片段在不同的窗口中工作,并且不在我们定义的 navController 的相同视图层次结构下。

在这种情况下,我们需要从 navHostFragment 中找到我们的 navController,然后进行导航:

someButton.setOnClickListener { view ->
                val action =
                    DestinationFragmentDirections.actionCurrentFragmentToDestinationFragment()
                val navHostFragment =
                    requireActivity().supportFragmentManager
                        .findFragmentById(R.id.nav_host_fragment_container) as NavHostFragment
                navHostFragment.navController.navigate(action)
            }
于 2021-09-13T15:48:59.270 回答