Android中NavigationComponent跳转传参报错的解决方法
使用NavigationComponent管理RecipesFragment与MenuFragment的跳转及数据传递,已在RecipesFragment中定义带默认值的布尔参数isUpdatedData,但从MenuFragment跳转回RecipesFragment时,调用自动生成的actionMenuFragmentToRecipesFragment(true)传入参数,出现报错:
Too many arguments for public open fun actionMenuFragmentToRecipesFragment(): MenuFragmentDirections.ActionMenuFragmentToRecipesFragment defined in myapp.ui.fragments.recipe.menu.MenuFragmentDirections
导航配置代码:
<navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/nav_home" app:startDestination="@id/recipesFragment"> <fragment android:id="@+id/recipesFragment" android:name="myapp.ui.fragments.recipe.RecipesFragment" android:label="@string/recipes" tools:layout="@layout/fragment_recipes" > <action android:id="@+id/action_recipesFragment_to_menuFragment" app:destination="@id/menuFragment" /> <argument android:name="isUpdatedData" app:argType="boolean" android:defaultValue="false" /> </fragment> <dialog android:id="@+id/menuFragment" android:name="myapp.ui.fragments.recipe.menu.MenuFragment" android:label="fragment_menu" tools:layout="@layout/fragment_menu" > <action android:id="@+id/action_menuFragment_to_recipesFragment" app:destination="@id/recipesFragment" /> </dialog> </navigation>
MenuFragment跳转代码:
submitBtn.setOnClickListener { val action = MenuFragmentDirections.actionMenuFragmentToRecipesFragment(true) findNavController().navigate(action) }
问题核心:仅在目标Fragment(RecipesFragment)中定义参数,但从MenuFragment到RecipesFragment的跳转action未关联该参数,导致自动生成的MenuFragmentDirections类中,actionMenuFragmentToRecipesFragment方法无参数输入项。
按以下步骤修复:
修改导航配置,为跳转action添加参数
打开导航XML,在menuFragment的action_menuFragment_to_recipesFragment节点内添加对应参数,明确该跳转需要传递参数到目标Fragment:<dialog android:id="@+id/menuFragment" android:name="myapp.ui.fragments.recipe.menu.MenuFragment" android:label="fragment_menu" tools:layout="@layout/fragment_menu" > <action android:id="@+id/action_menuFragment_to_recipesFragment" app:destination="@id/recipesFragment" > <!-- 与目标Fragment参数保持一致 --> <argument android:name="isUpdatedData" app:argType="boolean" android:defaultValue="false" /> </action> </dialog>也可直接引用目标Fragment已定义的参数,写法更简洁:
<argument android:name="isUpdatedData" app:arg="@argument/isUpdatedData" />重新编译项目
Navigation的Directions类为自动生成,修改XML后需执行Rebuild Project或Make Project,让系统重新生成带参数的actionMenuFragmentToRecipesFragment方法。验证跳转代码
此时调用MenuFragmentDirections.actionMenuFragmentToRecipesFragment(true)即可正常传递参数,不会再报错。
内容的提问来源于stack exchange,提问作者Dr.KeyOk

