Reputation: 753
I am using the navigation component for navigation between bottom Navigation view fragments. But the fragment states are saving, it is creating everytime I visit that menu item.
As per this update - https://developer.android.com/jetpack/androidx/releases/navigation#2.5.0-alpha04 the component is saving the state.
Upvotes: 2
Views: 2949
Reputation: 3804
It is not possible as of navigation component version 2.7.6. Trust me I tried everything. Whenever you switch the bottomNavigationBar using Navigation Component, the new tabs will recreate the fragment every time. This is not a soft recreate where the instance of fragment is the same so you can save the view and return it every time, the fragments themselves are recreated.
For example, when you have tabs A, B, and C and you start with tab A. When you switch tab to B, the fragment B will be recreated as a new instance with all of its variables reset to null. When you go to C, the same thing. When you go back to A however, it will not create a new instance of fragment A, instead it will be the same instance, but the onCreateView will be called at which you can just return the saved rootView to restore the state. There is no way to "restore" the state like A in B and C. It is just not possible. You need to come up with another way. Google documentations/blogs are misleading, and there is no way to restore fragments from the other tabs that is not the first/initial tab.
Upvotes: 0
Reputation: 571
Fragment state will be retained in Jetpack Navigation for only the views which have "id" set on them. Views which don't have any "id" will not retain their state. Also, you should use AppBarConfiguration with NavController. There are examples with AppBarConfiguration to look up.
And last and foremost, don't use "app:popUpTo" & "app:popUpToInclusive" attributes in navigation graph xml file for actions. That will pop all the fragments, till that "app:popUpTo" fragment in back stack once the action is triggered.
Upvotes: 2
Reputation: 23
if you don't want to save your fragment to the backstack, use this line to nav_graph of this fragment
<fragment
android:id="@+id/fragment1"
android:name="fragmentClassName" >
<action
android:id="@+id/action_Fragment1_to_Fragment2"
app:destination="@id/Fragment2_id"
app:popUpTo="@+id/your_root_graph_id"
app:popUpToInclusive="true" />
Upvotes: -2