我有一个包含 NavHostFragment 的 BottomSheetDialogFragment,如下所示:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/add_feeling_nav_host_fragment"
android:name="androidx.navigation.fragment.NavHostFragment"
android:layout_width="match_parent"
android:layout_height="0dp"
app:defaultNavHost="true"
app:navGraph="@navigation/add_feeling_graph" />
</LinearLayout>
</layout>
当我尝试使用以下任一方法在其类中获取 NavController 时:
activity?.findNavController(R.id.add_feeling_nav_host_fragment)
view.findNavController()
第一个选项崩溃,因为它找不到 ID,而第二个选项确实找到了父导航 Controller 并使用它。
我对另一个 Fragment 有相同的设置,但它不是一个对话框,它工作得很好。有什么想法可能是什么问题?谢谢
最佳答案
activity?.findNavController(R.id.add_feeling_nav_host_fragment)
不会做这项工作 - 只有当对话框 fragment 处于 Activity 状态(显示)并且它是 Activity 的 UI 容器的一部分时才会起作用 - DialogFragment
在与根导航图不在同一层次结构内的其他窗口实例中工作。
适当的方法 - 使用 NavHostFragment.findNavController(fragment)
或 ktx
分机 fragment.findNavController()
在哪里 fragment
是你的对话 fragment 。对话框 fragment 应该在其 View 膨胀的情况下显示。最好的方法 - 在对话框中。
可能还需要调整导航图 - 由于没有代码,我无法准确判断。
希望能帮助到你。
关于android - 无法找到 DialogFragment 中的 NavController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57930643/