Android Kotlin跨导航图跳转报错:传递参数时参数过多
错误原因
- 导航配置中
FavoritesFragment的action存在两处问题:- action的id命名与目标页面不匹配(id为
action_favoritesFragment_to_homeNavigation,但实际目标是detailsFragment),导致自动生成的导航方向类方法不符合预期。 - 该action未声明需要传递的
movieItem参数,因此生成的actionFavoritesFragmentToHomeNavigation()方法不接收参数,代码中传递MovieModelItem对象就会触发「参数过多」的编译错误。
- action的id命名与目标页面不匹配(id为
修复步骤
1. 修正nav_graph.xml的导航配置
修改FavoritesFragment下的action,调整id并添加对应参数:
<fragment android:id="@+id/favoritesFragment" android:name="com.tito.movieapps.ui.fragments.FavoritesFragment" android:label="@string/favorites" tools:layout="@layout/fragment_favorites" > <!-- 修改action的id为对应目标页面的命名,同时指定目标 --> <action android:id="@+id/action_favoritesFragment_to_detailsFragment" app:destination="@id/detailsFragment" /> <!-- 添加与DetailsFragment一致的参数声明 --> <argument android:name="movieItem" app:argType="com.tito.domain.entites.MovieModelItem" /> </fragment>
2. 调整FavoritesFragment中的跳转代码
使用修正后的导航方向方法传递参数:
override fun onItemClick(movieModelItem: MovieModelItem) { // 使用正确的导航方向方法,传递MovieModelItem参数 val directions = FavoritesFragmentDirections.actionFavoritesFragmentToDetailsFragment(movieModelItem) findNavController().navigate(directions) }
额外确认
确保MovieModelItem类已正确实现Parcelable接口(你之前在首页跳转时已正常使用,这一步大概率没问题,但可以再次确认)。
内容的提问来源于stack exchange,提问作者Ahmed Elsayed
相关产品推荐
相关产品推荐

