gpt4 book ai didi

android - 当参数具有默认值时,为什么我不能使用导航组件将参数传递给 fragment ?

转载 作者:行者123 更新时间:2023-12-04 09:23:36 26 4
gpt4 key购买 nike

我正在使用导航组件,但如果定义了参数,我不明白为什么将参数传递给下面的方法时会出错。我正在使用 SafeArgs,只有在为此参数定义默认值时才会出现此错误。
enter image description here
有人可以解释一下为什么会发生这种情况,我该如何解决?
这是导航图的一部分代码。

<fragment
android:id="@+id/sleepTrackerFragment"
android:name="com.example.sleeptracker.fragments.sleep_tracker.SleepTrackerFragment"
android:label="fragment_sleep_tracker"
tools:layout="@layout/fragment_sleep_tracker" >
<action
android:id="@+id/action_sleepTrackerFragment_to_sleepQualityFragment"
app:destination="@id/sleepQualityFragment" />
<argument
android:name="qualityLastSleep"
app:argType="integer"
android:defaultValue="-1" />
</fragment>
<fragment
android:id="@+id/sleepQualityFragment"
android:name="com.example.sleeptracker.fragments.sleep_quality.SleepQualityFragment"
android:label="fragment_sleep_quality"
tools:layout="@layout/fragment_sleep_quality" >
<action
android:id="@+id/action_sleepQualityFragment_to_sleepTrackerFragment"
app:destination="@id/sleepTrackerFragment" >
</action>
</fragment>

最佳答案

如文档中所述

Destination-level arguments and default values are used by all actions that navigate to the destination. If needed, you can override the default value of an argument (or set one if it doesn't already exist) by defining an argument at the action level. This argument must be of the same name and type as the argument declared in the destination.


因此您必须覆盖此值才能执行此操作,以便您可以遵循以下两种解决方案中的任何一种
解决方案一
 val action =  SleepQualityFragmentDirections.actionSleepQualityFragmentToSleepTrackerFragment()
action.qualityLastSleep = 5 // your value
findNavController().navigate(action)

解决方案二
<fragment
android:id="@+id/sleepTrackerFragment"
android:name="com.example.sleeptracker.fragments.sleep_tracker.SleepTrackerFragment"
android:label="fragment_sleep_tracker"
tools:layout="@layout/fragment_sleep_tracker" >
<argument
android:name="qualityLastSleep"
app:argType="integer"
android:defaultValue="-1" />
<action
android:id="@+id/action_sleepTrackerFragment_to_sleepQualityFragment"
app:destination="@id/sleepQualityFragment" />
</fragment>
<fragment
android:id="@+id/sleepQualityFragment"
android:name="com.example.sleeptracker.fragments.sleep_quality.SleepQualityFragment"
android:label="fragment_sleep_quality"
tools:layout="@layout/fragment_sleep_quality" >

<action
android:id="@+id/action_sleepQualityFragment_to_sleepTrackerFragment"
app:destination="@id/sleepTrackerFragment" >
<argument
android:name="qualityLastSleep"
app:argType="integer"
android:defaultValue="-1" />

</action>
</fragment>
然后你可以像这样调用你的导航
findNavController().navigate(SleepQualityFragmentDirections.actionSleepQualityFragmentToSleepTrackerFragment(5))

关于android - 当参数具有默认值时,为什么我不能使用导航组件将参数传递给 fragment ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63058373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com