Vladd313
Vladd313

Reputation: 11

How to navigate to fragment with arguments without recreating it?

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?

Upvotes: 1

Views: 1420

Answers (3)

yan sam
yan sam

Reputation: 427

<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

Upvotes: 0

Robin
Robin

Reputation: 1345

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

Upvotes: 1

SkypeDogg
SkypeDogg

Reputation: 1040

I think SavedStateHandle might be helpful.

Upvotes: 0

Related Questions