RallyApp with custom navigation transitions
This is a an example of how to use a modified NavHost
that allows a degree of customisation for the transition.
The original source code is from the
Navigation in Jetpack Compose Codelab.
ModdedNavHost.kt is a modified version of NavHost
from the navigation compose library, though specifically the hardcoded Crossfade
has been replaced with a more flexible AnimatedContent
. The overloaded NavHost
composables take a NavTransition
that offer some flexibility. Other than that, it is effectively the same.
To briefly go over the API modification, lets say you define your routes with an enum such as:
enum class Route {
A, B;
companion object {
fun from(navBackStackEntry: NavBackStackEntry?): Route? =
navBackStackEntry.routeName?.let { routeName: String ->
try {
valueOf(routeName)
} catch (e: IllegalArgumentException) {
null
}
}
private val NavBackStackEntry?.routeName: String?
get() = this?.destination?.route?.substringBefore('/')
}
Then all you have to add to your NavHost is a NavTransition
, optionally using a built in factory such as NavTransition.horizontalSlideFade
:
NavHost(
navController = navController,
startDestination = Route.A.name,
// this transition property is the addition
transition = NavTransition.horizontalSlideFade { initial: NavBackStackEntry, target: NavBackStackEntry ->
Route.from(initial)!!.compareTo(Route.from(target)!!)
},
modifier = modifier,
) {
// graph definition
}
Horizontal transition:
navigation_horizontal.mp4
Vertical transition:
navigation_vertical.mp4
Fade out > fade in transition (not as nice as crossfade admitedly):