androidx 导航:@NonNull 公共开放乐趣的参数太多

Ana*_*nth 7 android android-studio android-jetpack androidx android-jetpack-navigation

我在 Android Studio 中使用导航编辑器来实现Safe Args.

我在一个片段中接受参数为

 <fragment
    android:id="@+id/gameWonFragment"
    android:name="com.example.android.navigation.GameWonFragment"
    android:label="@string/android_trivia"
    tools:layout="@layout/fragment_game_won">

    <action
        android:id="@+id/action_gameWonFragment_to_gameFragment"
        app:destination="@id/gameFragment"
        app:popUpTo="@+id/titleFragment">
    </action>
    <argument
        android:name="numQuestions"
        app:argType="integer"
        android:defaultValue="0" />
    <argument
        android:name="numCorrect"
        app:argType="integer"
        android:defaultValue="0" />
 </fragment>
Run Code Online (Sandbox Code Playgroud)

在我的片段中,我将参数发送为

view.findNavController().navigate(GameFragmentDirections.actionGameFragmentToGameWonFragment(numQuestions, questionIndex))
Run Code Online (Sandbox Code Playgroud)

但是,GameFragmentDirections.actionGameFragmentToGameWonFragment()不想接受论据。我试过Clean ProjectRebuild Project

这是抛出:

Too many arguments for @NonNull public open fun actionGameFragmentToGameWonFragment(): GameFragmentDirections.ActionGameFragmentToGameWonFragment defined in com.example.android.navigation.GameFragmentDirections
Run Code Online (Sandbox Code Playgroud)

Ana*_*nth 21

此问题是由固定去除android:defaultValue标签。

所以 -

<argument
    android:name="numQuestions"
    app:argType="integer"/>
<argument
    android:name="numCorrect"
    app:argType="integer"/>
Run Code Online (Sandbox Code Playgroud)

然后Rebuild Project进行更改后。


小智 8

这是在这里的类似帖子中回答的 - /sf/answers/4256556601/

基本上,您可能需要像这样使用 Kotlin 版本的插件apply plugin: "androidx.navigation.safeargs.kotlin"


小智 7

我也遇到过这个问题。android:defaultValue通过获取适当的操作对象的实例,设置必要的值,然后将其发送到导航命令,我能够保留参数标签并清除“参数过多”错误。

所以,例如,这个:

val actionDetail = GameFragmentDirections.actionGameFragmentToGameWonFragment()
actionDetail.numQuestions = numQuestions
actionDetail.numCorrect = questionIndex
view.findNavController().navigate(actionDetail)
Run Code Online (Sandbox Code Playgroud)

而不是这个:

view.findNavController().navigate(GameFragmentDirections.actionGameFragmentToGameWonFragment(numQuestions, questionIndex))
Run Code Online (Sandbox Code Playgroud)