Skip to content

Animations

If you want to show animated transitions between destinations use AnimatedNavHost. The default transition is a simple crossfade, but you can granularly customize every transition with your own NavTransitionSpec implementation.

Here is one possible implementation of NavTransitionSpec:

val CustomTransitionSpec = NavTransitionSpec<Any?> { action, _, _ ->
    val direction = if (action == NavAction.Pop) {
        AnimatedContentTransitionScope.SlideDirection.End
    } else {
        AnimatedContentTransitionScope.SlideDirection.Start
    }
    slideIntoContainer(direction) togetherWith slideOutOfContainer(direction)
}

Set it into AnimatedNavHost:

AnimatedNavHost(
    controller = navController,
    transitionSpec = CustomTransitionSpec
) { destination ->
    // ...
}

and it'll end up looking like this:

In NavTransitionSpec you get the parameters:

  • action - a hint about the last NavController method that changed the backstack
  • from - a previous visible destination
  • to - a target visible destination

This information is plenty enough to choose a transition for every possible combination of destinations and navigation actions.

Tip

You can add more enter/exit animations to the composables through the AnimatedNavHostScope receiver of the contentSelector parameter. AnimatedNavHostScope gives you access to the current transition and to animateEnterExit modifier.

There are four default NavAction types:

  • Pop, Replace and Navigate - objects that correspond to pop…, replace…, navigate methods of NavController
  • Idle - the default action of a newly created NavController. You don't need to handle it in NavTransitionSpec.

You can also create new action types by implementing NavAction interface. Pass any object of the new type into setNewBackstack method of NavController and handle it in NavTransitionSpec.

The last action can also be accessed through action property of NavBackstack.