architecture-components-samples
architecture-components-samples copied to clipboard
Navigate deeplinks without restarting app
Using handle deeplinks restarts the app to create correct backstack but to open deeplink in advance bottom navigation without restarting app.
fun BottomNavigationView.navigateDeeplink(
navGraphIds: List<Int>,
fragmentManager: FragmentManager,
containerId: Int,
uri: Uri) {
navGraphIds.forEachIndexed { index, navGraphId ->
val fragmentTag = getFragmentTag(index)
// Find or create the Navigation host fragment
val navHostFragment = obtainNavHostFragment(
fragmentManager,
fragmentTag,
navGraphId,
containerId
)
// Handle deeplink
val canHandleDeeplink = navHostFragment.navController.graph.hasDeepLink(uri)
if (canHandleDeeplink) {
if (selectedItemId != navHostFragment.navController.graph.id) {
selectedItemId = navHostFragment.navController.graph.id
}
navHostFragment.lifecycleScope.launchWhenResumed {
// Wait for fragment to restore state from backStack
// otherwise navigate will be ignored
// Ignoring navigate() call: FragmentManager has already saved its state
navHostFragment.navController.navigate(uri)
}
}
}
}
The above solution has an issue that it will create multiple instance of same fragment. To avoid multiple instance and restart check this sample app for SingleActivity Architecture with multiple backstack https://github.com/beetlestance/android-extensions/tree/main/navigation