导航组件Kotlin-从当前目的地找不到 [英] Navigation component Kotlin - cannot be found from the current destination
问题描述
我有一个片段A,B,C.从A->导航时还可以.B,但来自B->C崩溃了.
I have a fragment A,B,C. Its okay when navigating from A -> B, but from B -> C it crashes.
这是我的导航
这是我的导航代码
categoryProductItemListAdapter.setOnItemClickListener {
val action = CategoryProductItemsDirections.actionCategoryProductItems2ToProductItem(null, it)
navController = Navigation.findNavController(requireView())
navController?.navigateUp()
navController?.navigate(action)
}
这是productItem目的地的XML代码
Here is the XML code for the destination to productItem
<fragment
android:id="@+id/categoryProductItems2"
android:name="com.sample.store.main.dashboard.ui.ui.home.categoryitems.CategoryProductItems"
android:label="CategoryProductItems"
tools:layout="@layout/fragment_category_product_items">
<argument
android:name="category_global"
app:argType="com.sample.store.data.globalmodels.response.categories.Category" />
<action
android:id="@+id/action_categoryProductItems2_to_productItem"
app:destination="@id/productItem"
app:enterAnim="@anim/enter_from_right"
app:exitAnim="@anim/exit_to_right"
app:popEnterAnim="@anim/fragment_open_enter"
app:popExitAnim="@anim/fragment_fade_exit" />
</fragment>
这是错误:
java.lang.IllegalArgumentException: Navigation action/destination com.sample.store.full:id/action_categoryProductItems2_to_productItem cannot be found from the current destination Destination(id/navigation_home) label=Home class=com.sample.store.main.dashboard.ui.ui.home.mainui.HomeFragment
我不知道发生了什么,但似乎navController正在寻找"navigation_home"
I don't know what happened, but it seems that the navController is looking for the "navigation_home"
推荐答案
首先,在尝试检索Nav控制器时,您不应传递 requireView()
- navController = Navigation.findNavController(requireView())
.您应该传递实际的Navigation Host Fragment实例.
Firstly you should not pass requireView()
when trying to retrieve your Nav controller - navController = Navigation.findNavController(requireView())
. You should be passing the actual Navigation Host Fragment instance.
第二个原因是由于您试图从B调用导航路径而引起的.C,在片段A上.
Secondly the issue is being caused because you are trying to call a Navigation path from B -> C, when on fragment A.
您的方向路径来自B->C
Your direction path is from B -> C
val action = CategoryProductItemsDirections.actionCategoryProductItems2ToProductItem(null, it)
但是您首先要向上导航,所以实际上在尝试执行导航时您现在位于Fragment A上:
But you navigate up first so you are actually now on Fragment A when trying to execute the navigation:
navController?.navigateUp()
navController?.navigate(action)
这篇关于导航组件Kotlin-从当前目的地找不到的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!