使用Navigation组件向嵌套导航图传Parcelable参数时生成函数无参问题
你遇到的问题根源是参数定义的位置和跳转目标不匹配:你当前的跳转动作action_productDetailFragment_to_loginAndRegisterFragment的目标是login_nav_graph这个嵌套导航图本身,而非导航图内部的loginAndRegisterFragment。参数定义在子导航图的内部Fragment上时,父导航图的跳转动作无法感知到该参数,因此生成的Directions函数不会携带入参。
你可以选择以下任意一种方案解决:
方案1:将参数提升到嵌套导航图根节点(推荐,适合子导航图多页面共享参数的场景)
修改login_nav_graph.xml,把product参数从loginAndRegisterFragment内部移到<navigation>根节点下:
<?xml version="1.0" encoding="utf-8"?> <navigation android:id="@+id/login_nav_graph" app:startDestination="@id/loginAndRegisterFragment" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto"> <!-- 把参数移到嵌套导航图根节点 --> <argument android:name="product" app:argType="com.vendyapp.vendy.features.loggedcontent.home.Product" app:nullable="true" /> <fragment android:id="@+id/loginAndRegisterFragment" android:name="com.vendyapp.vendy.features.login.ui.LoginAndRegisterFragment" android:label="fragment_login_and_register" tools:layout="@layout/fragment_login_and_register"> <action android:id="@+id/action_loginAndRegisterFragment_to_registerFragment" app:destination="@id/registerFragment" /> <action android:id="@+id/action_loginAndRegisterFragment_to_loginFragment" app:destination="@id/loginFragment" /> </fragment> </navigation>
子导航图内的页面需要获取参数时,可直接从导航图的arguments取值,也可在Fragment的argument标签中通过app:defaultValue="@navGraphArgs.product"引用导航图参数,无需手动传递。
方案2:修改跳转动作的目标为具体Fragment
直接修改父导航图的跳转动作,把destination改为子导航图内loginAndRegisterFragment的ID:
<action android:id="@+id/action_productDetailFragment_to_loginAndRegisterFragment" app:destination="@id/loginAndRegisterFragment" />
这种方式无需修改子导航图的参数位置,适合仅需要给子导航图内单个页面传参的场景。
修改完成后清理项目重新编译,自动生成的Directions函数就会携带product入参,原有调用代码可正常运行。
内容的提问来源于stack exchange,提问作者marcpetitvecino
相关产品推荐
相关产品推荐

