I have a String
type arg send from NewCodeFragment
to MainFragment
.
If I set a default value, then I got a 'too many args' error.
How can I set a default value? My understanding is if I send a arg, then the destination fragment will receive the arg, else it will receive the default value. Wrong?
Problem code:
navigation
XML:
<argument
android:name="aArg"
app:argType="string"
app:nullable="true"
android:defaultValue="@null" />
fragment.class
:
val aArg="abc"
// build error, it says too many args
this.findNavController().navigate(NewCodeFragmentDirections.actionNewCodeFragmentToMainFragment(aArg))
No problem code:
navigation
XML:
<argument
android:name="aArg"
app:argType="string"
app:nullable="true"/> // remove android:defaultValue="@null"
fragment.class
:
val aArg="abc"
this.findNavController().navigate(NewCodeFragmentDirections.actionNewCodeFragmentToMainFragment(aArg))
Another no problem code:
navigation
XML:
<argument
android:name="aArg"
app:argType="string"
app:nullable="true"
android:defaultValue="@null" />
fragment.class
:
val aArg="abc"
this.findNavController().navigate(NewCodeFragmentDirections.actionNewCodeFragmentToMainFragment()) // remove aArg
I like the last approach. Here argument can have default value. If you have a standard value instead of passing it in the argument my suggestion would be you keep it in the destination fragment that will receive the arguments. So, you won't have to add the same default string everywhere. If the
defaultValue
fromargs
isnull
, you can use the value on that fragment.For example, 3 Fragments A, B and C are going Fragment X with args. A passes
"abc"
, B and C passnull
. Now you can have the condition in Fragment X when reading from the args,