Reputation: 455
I have four fragment in bottom navigation and one activity, Bottom navigation is set up using NavController like this
navController = Navigation.findNavController(this, R.id.dashboardNavHostFragment).apply {
setGraph(R.navigation.nav_graph , bundle)
}
bottomNavigationView.setupWithNavController(navController)
I'm passing some data in bundle that I require in my first fragment of bottom nav. The problem is it works fine the data comes in the fragment like this
private val args: PlayerFeedFragmentArgs by navArgs()
private var data: String? = args.name
but when I navigate using bottom nav and come back to my first fragment the data comes as null I tried saving data using
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("name", data)
}
and getting data back in onViewCreated but it didn't work because onSaveInstanceState does not get called when switching between fragments of bottom nav.
How can I save the incoming args from the activity in my first fragment so that when I switch fragments from bottom nav it stays the same.
Upvotes: 4
Views: 4020
Reputation: 1237
You can try using a SavedStateViewModel handler
https://developer.android.com/reference/kotlin/androidx/lifecycle/SavedStateViewModelFactory
A quick example can be found here:
Using this method, you don't have to share your data with other fragments.
Upvotes: 1