Custom Animation (Android)

Pushing

You can change the default Android push animation by creating an Android animation resource file. In our example email application, we want the 'mail' scene to slide in from the right when a user opens an email. Inside Android Studio, we right click the root of our project and choose 'New -> Android Resource File'. In the pop-up dialog, we enter a name of 'slide_in', pick 'Animation' from the resource type dropdown and enter 'anim' for the directory name. We configure our 'slide_in' animation as a translation of the scene's x coordinate from 100% to 0.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
  <translate
    android:duration="300"
    android:fromXDelta="100%"
    android:toXDelta="0" />
</set>

To get this animation to play when the mail scene starts mounting, we attach a getUnmountStyle function to the corresponding 'mail' State. When we navigate to the 'mail' State, the Navigation router calls this function and we return the name of our animation resource file.

var {mail} = stateNavigator.scenes;
mail.getUnmountStyle = from => from ? 'slide_in' : null;

Popping

Changing the default pop animation is similar to the way you change the push animation. In our email example, we want to slide the 'mail' scene back out to the right when a user returns to their inbox. We create an animation resource file called 'slide_out'. It’s the same as 'slide_in' but with the x coordinate values reversed, so that the scene goes back out the way it came in.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
  <translate
    android:duration="300"
    android:fromXDelta="0"
    android:toXDelta="100%" />
</set>

When we navigate back from the 'mail' State, the Navigation router calls the getUnmountStyle function again. This time the from parameter it passes in is false. We return our resource file name and the Navigation router slides the scene out as it unmounts.

var {mail} = stateNavigator.scenes;
mail.getUnmountStyle = from => from ? 'slide_in' : 'slide_out';

Animating Crumbs

When you push a new scene onto the stack, you can animate the outgoing scene as well as the incoming one. We want to fade out the 'inbox' scene when the user opens an email and fade it back in when they return to their inbox. We create two animation resource files. One called 'fade_out' that changes the scene's alpha value from 1 to 0, and another called 'fade_in' that changes it back again.

The Navigation router calls the getCrumbStyle function attached to the 'inbox' State to find out how to animate the 'inbox' scene. When the user opens an email the Navigation router calls the function passing in 'false' and, when the user returns to their inbox, it calls the function again with 'true'.

var {inbox} = stateNavigator.scenes;
inbox.getCrumbStyle = from => from ? 'fade_in' : 'fade_out';