Adding animations to your Jetpack Compose navigation
With Jetpack Compose going stable in a 1.0 release recently you might be tempted to give it a go. If you opt to go for the compose-navigation component, you will however notice that the ability to add different animations between your screens is not there. What you are left with is the following experience.
If you see this as a deal breaker, there is light at the end of the tunnel. Accompanist, a project with various compose utilities, recently added support for animations together with the 2.4.0-alpha06 version of navigation-compose. To be able to use the experimental animation support make sure your gradle file has the two following dependencies.
implementation "androidx.navigation:navigation-compose:2.4.0-alpha06" implementation "com.google.accompanist:accompanist-navigation-animation:0.16.0"
You should now have access to the new AnimatedNavHost composable as well as a new variant of the composable extension function used with the NavGraphBuilder and the new rememberAnimatedNavController function. Swap your old code with these in your code to start getting the custom animated goodness.
A graph without animation would look like this:
With rememberNavController() exchanged for rememberAnimatedNavController(), NavHost(…) exchanged for AnimatedNavHost and finally replace the import of androidx.navigation.compose.composable with com.google.accompanist.navigation.animation.composable (note that it’s the composable with a small c not the composable with a big C from androidx.compose.runtime.Composable)
We then end up with code that looks like this:
Notice the addition, of the @ExperimentalAnimationApi annotation as well as we are using experimental api’s, but your android studio will probably let you know if you haven’t added it already.
With the usage of the new experimental composable(…) function we get access to 4 more arguments, enterTransition, exitTransition, popEnterTransition and popExitTransition.
These are going to be familiar if you have previously set up animations in the old xml world of the jetpack navigation component.
These argument takes transition objects and we can then create a composable that looks like this:
The neat thing about these is that the animationSpec are normal compose animation specs so you can use both physically spring based animations and interpolation based animations like this:
Tip: if you want a nice editor of bezier curves check out https://cubic-bezier.com/
In the end you are then left with the ability to make navigation like this:
Keep in mind that these API’s are experimental so be cautious about using them in a production app for now.
For a full example both with and without animations, check out the repository for this post on github.