architecture-components-samples icon indicating copy to clipboard operation
architecture-components-samples copied to clipboard

Navigate deeplinks without restarting app

Open akshay253101 opened this issue 5 years ago • 1 comments

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 avatar May 15 '20 07:05 akshay253101

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

akshay253101 avatar Jul 27 '20 02:07 akshay253101