Android Beginners

Lesson 15: Navigating Between Screens

Ahmad Najar Ahmad Najar 1 min read

So far we've only had one screen. Real apps need several. Let's add Navigation Compose so tapping a task opens its detail screen.

Add the dependency

// build.gradle.kts
implementation("androidx.navigation:navigation-compose:2.8.0")

Click "Sync Now" after adding this.

Define your screens as routes

@Serializable object TaskListRoute
@Serializable data class TaskDetailRoute(val taskId: Int)

(You'll also need the Kotlin serialization plugin — Android Studio will prompt you to add it automatically the first time you use @Serializable.)

Set up the NavHost

@Composable
fun AppNavHost() {
    val navController = rememberNavController()

    NavHost(navController = navController, startDestination = TaskListRoute) {
        composable {
            TaskListScreen(
                onTaskClick = { taskId ->
                    navController.navigate(TaskDetailRoute(taskId))
                }
            )
        }
        composable { backStackEntry ->
            val route: TaskDetailRoute = backStackEntry.toRoute()
            TaskDetailScreen(taskId = route.taskId)
        }
    }
}

Wire it into MainActivity

setContent {
    AppNavHost()
}

What each piece does

  • NavHost — the container that swaps screens in and out
  • navController.navigate(...) — moves forward to a new screen
  • startDestination — which screen shows first when the app opens

Update TaskListScreen from lesson 14 to accept an onTaskClick: (Int) -> Int parameter and call it when a task is tapped, passing the task's id. This is the same "function as parameter" pattern from lesson 4 — the list screen doesn't need to know how navigation works, it just calls the function it was handed.

Next: Lesson 16 — passing more complex data between screens properly.

Android Beginners