Home > Software design >  How to navigate to fragment with arguments without recreating it?
How to navigate to fragment with arguments without recreating it?

Time:12-02

I have a question. I'm using nav component for navigation. For example i have fragment A, B and C and bottomNavigation. I'm using

binding.bottomNavigation.setupWithNavController(navController)

For multiple backstack. But here is situation: Main frag is A. I'm moving to fragment B or C. I have buttons on fragments B and C which should lead me to fragment A with putted arguments in it so i'm using just:

findNavController().navigate(fragmentBDirections.fromFragmentBToFragmentA(argument))

But here is a problem. I'm recreating fragment A after this but i'm already have this fragment in backstack. So is it possible to find A in backstack and navigate to it without recreating? Is it possible to save backstack after that?

CodePudding user response:

Your problem seems like an ideal case to use a sharedViewModel

Your button in B or C should pop and fallback to A after updating a property in the viewModel. On leaving, the viewModel is not destroyed because it is bound to the activity and is available for Fragment A.

Bonus is using LiveData so that the change is observed and updated automatically

CodePudding user response:

I think SavedStateHandle might be helpful.

CodePudding user response:

<Navigation>
<fragment
        android:id="@ id/BFragment"
        android:name="com.packageName.app.BFragment"
        android:label="fragment_b"
        tools:layout="@layout/fragment_b" >
        <action
            android:id="@ id/action_BFragment_pop_including_AFragment"
            app:popUpTo="@id/AFragment"
            app:launchSingleTop="true" />
</Navigation>
<Navigation>
<fragment
        android:id="@ id/CFragment"
        android:name="com.packageName.app.CFragment"
        android:label="fragment_c"
        tools:layout="@layout/fragment_c" >
        <action
            android:id="@ id/action_CFragment_pop_including_AFragment"
            app:popUpTo="@id/AFragment"
            app:launchSingleTop="true" />
</Navigation>

try it . it's my solution

  • Related