How to handle navigation in Jetpack Compose?
New Jetpack lib has published for Compose navigation. It is still in alpha.
In this new library, now user can able to navigation between different composables with navigation components features.
Using navigation-compose:
dependencies {
def nav_compose_version = "1.0.0-alpha01"
implementation "androidx.navigation:navigation-compose:$nav_compose_version"
}
Example:
Step 1: create a NavController
by using the rememberNavController()
method in your composable: Link:
val navController = rememberNavController()
Step 2: Creating the NavHost
requires the NavController
previously created via rememberNavController()
and the route of the starting destination of your graph:Link.
NavHost(navController, startDestination = "profile") {
composable("profile") { Profile(...) }
composable("friendslist") { FriendsList(...) }
...
}
Step 3: To navigate to a composable use navigate()
:
fun Profile(navController: NavController) {
...
Button(onClick = { navController.navigate("friends") }) {
Text(text = "Navigate next")
}
...
}
check more https://developer.android.com/jetpack/compose/navigation
Here is an unofficial approach of navigation in Jetpack Compose. Try it out until you get an official word from the Google android devs.
compose-router
https://github.com/zsoltk/compose-router
Use androidx.navigation:navigation-compose
. See @pRaNaY's answer.
Original Answer
It seems that they are moving away from XML.
The new official samples released after the release of 1.0.0-alpha, have a shared code to manage backstack and navigation. This code is not part of the library yet.
https://github.com/android/compose-samples/blob/master/Owl/app/src/main/java/com/example/owl/ui/utils/Navigation.kt https://github.com/android/compose-samples/blob/master/Jetsnack/app/src/main/java/com/example/jetsnack/ui/utils/Navigation.kt
Update
Because sample projects are migrated to androidx.navigation:navigation-compose
, links are dead.
I tried to find the most up to date commits which links are not dead.
https://github.com/android/compose-samples/blob/17b362f0315cf786d3d77d6964ee39b50e311199/Owl/app/src/main/java/com/example/owl/ui/utils/Navigation.kt
https://github.com/android/compose-samples/blob/17b362f0315cf786d3d77d6964ee39b50e311199/Jetsnack/app/src/main/java/com/example/jetsnack/ui/utils/Navigation.kt