android / architecture-components-samples

Samples for Android Architecture Components.
https://d.android.com/arch
Apache License 2.0
23.4k stars 8.29k forks source link

Navigate deeplinks without restarting app #839

Open akshay253101 opened 4 years ago

akshay253101 commented 4 years ago

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)
            }
        }
    }
}
akshay253101 commented 4 years ago

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