Stop fragment Re-Creation in BottomNavigation using NavGraph

Viewed 55

I have multiple fragments like Dashboard,Notifications and Profile in Bottom Navigation. I am using NavGraph- NavController to control the fragments.

I want to save the state of previous fragment.

I don't want to call my API's again on Switching between fragments. Whenever I switch between fragment it calls onDestroyView of previous fragment and onCreateView of current Fragmnent . That's why all the operation in onCreateView or onViewCreated will call again.

How could I get rid of it. Is there any implementation using NavGraph that stop fragment from reCeating

Or is there a way to don't call those API's again . I mean to retatin the UIState.

For example: The user is on Map fragment and he search some location on Google Map and moves to the next fragment Dashboard

I have tried using

lifecycleScope.launch {
   lifecycleScope.launchWhenCreated {
        Log.v("LifeCycleState","launchWhenCreated")
   }
}
viewLifecycleOwner.lifecycleScope.launch {
    lifecycleScope.launchWhenCreated {
         Log.v("LifeCycleState","launchWhenCreated in viewLifeCycleOwner")
    }
}
1 Answers

You've to follow multi navigations graph concept.

Create separate graphs for the bottom nav icon based. Ex Home, History and Account So you've to create 3 graphs and include in one graph.

Like this

<navigation
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/nav_graph"
app:startDestination="@+id/home">

<include app:graph="@navigation/home"/>
<include app:graph="@navigation/history"/>
<include app:graph="@navigation/account"/>

Follow this sample

Related