Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Change Navigation Animation - Jetpack Compose

How can I change the navigation animation of the same destination when navigating in jetpack compose? For example, I want to show the screen horizontally from the right and other times I want that same screen to come vertically from the bottom (when clicking on a notification). I can't really do it using navController.navigate(route) because the route is defined on the same hierarchy as the enterTransition and exitTransition.

composable(
        route = "Details",
        deepLinks = listOf(navDeepLink { uriPattern = "myapp://test/details" }),
        enterTransition = {
                slideInVertically(
                    initialOffsetY = { it },
                    animationSpec = tween(durationMillis = 700, easing = LinearOutSlowInEasing)
                )
            }
        },
        exitTransition = {
            ExitTransition.None
        },
        popEnterTransition = {
            EnterTransition.None
        },
        popExitTransition = {
            slideOutVertically(
                targetOffsetY = { it },
                animationSpec = tween(durationMillis = 700, easing = LinearOutSlowInEasing)
            )
        },
    ) {
         MyComposable()
    }
like image 727
androiddev321 Avatar asked Oct 24 '25 14:10

androiddev321


1 Answers

You can utilize navigation arguments. Once you have set up the navigation arguments, you can access the argument value and adjust the transition behavior. Here's an example:

NavHost(..) {
    composable(
        route = "Details/{MyAnimation}",
        enterTransition = {
            val slideDirection = this.targetState.arguments?.getString("MyAnimation") ?: "start"
            val slideDirectionEnum = when (slideDirection) {
                "slideUp" -> AnimatedContentTransitionScope.SlideDirection.up
                "slideDown" -> AnimatedContentTransitionScope.SlideDirection.down
                else -> AnimatedContentTransitionScope.SlideDirection.start // default
            }

            fadeOut(
                animationSpec = tween(
                    durationMillis = 300,
                    easing = LinearEasing
                )
            ) + slideOutOfContainer(
                animationSpec = tween(durationMillis = 300, easing = EaseOut),
                towards = slideDirection
            )
        },
    ){
        MyComposable()
    }
    composable("OtherComposable"){
        OtherComposableScreen(
            onNavigateToDetails = { navController.navigate("Details/slideUp") }
        )
    }
}
like image 55
Ori S Avatar answered Oct 27 '25 05:10

Ori S