I'm trying to reuse a fragment in different navigation graphs with safe args enabled. I noticed that if the actions are different I get a compilation error. This is because the xxxFragmentDirections
autogenerated code will only generate one of the actions.
In nav_graph_1.xml:
<navigation
...
<fragment
android:id="@+id/myFragment"
android:name="com.example.android.MyFragment">
<action
android:id="@+id/next_action"
app:destination="@+id/dest_one" />
</fragment>
...
In nav_graph_2.xml:
<navigation
...
<fragment
android:id="@+id/myFragment"
android:name="com.example.android.MyFragment">
<action
android:id="@+id/other_action"
app:destination="@+id/other_dest" />
</fragment>
...
A simple use case: A bank app that has two flows: withdraw and deposit, therefore you could have two nav graphs. You could have an AmountFragment
where you could just enter a number and this could be reused to either withdraw or deposit. However, depending on the flow, the actions/destinations could be different.
Then, how would it be possible to reuse this fragment?
BaseAmountFragment
,WithdrawAmountFragment
and aDepositAmountFragment
? – Rustinclass CustomDirections private constructor() { private data class ActionFromFragmentToFragment( val arg: Arg? = null ) : NavDirections { override fun getActionId(): Int = R.id.action_id override fun getArguments(): Bundle {…} } companion object { fun actionFromFragmentToFragment(arg: Arg? = null): NavDirections = ActionFromFragmentToFragment(arg) } }
– Centrifugal