Skip to Content
Navigation

Compose Navigation

Compose Navigation is a Jetpack Compose library specifically designed for managing navigation within your Android applications built with Compose.

Usage

Dependencies

Within your app module’s build.gradle.kts file, incorporate the following dependencies:

implementation(project(":navigation:compose"))

Example

This guide walks you through configuring navigation within your app. It leverages a custom NavHost component and pre-defined routes for a streamlined setup.

Key Components

  • NavHost: This core component serves as the container for your application’s navigation graph. We’ve provided a custom AppNavHost component ready for use.
  • ScreenRoute Enum: This enum acts as a central source of truth for defining all your app’s navigation routes. Adding new screens involves simply creating a new entry within this enum.
  • Screen Class: This class represents an individual screen within your navigation flow. It specifies the route (ScreenRoute) and the composable function responsible for rendering the screen’s content.

Steps

  1. Integrate the provided AppNavHost composable within your MainActivity's Scaffold composable:
Scaffold { AppNavHost( modifier = Modifier.padding(it), navController = navController, screens = screens, startRoute = ScreenRoute.HOME, ) }

Provide the following properties:

  • navController: Reference to your navigation controller instance.
  • screens: List of Screen objects representing your app’s screens.
  • startRoute: The initial route to display when the app launches (e.g., ScreenRoute.HOME).
  1. Create a list of Screen objects in your MainActivity:
private val screens = listOf( Screen( route = ScreenRoute.HOME, content = { navBackStackEntry, navController -> HomeScreen(navController) } ), Screen( route = ScreenRoute.PROFILE, content = { navBackStackEntry, navController -> ProfileScreen(navController) } ), Screen( route = ScreenRoute.PROFILE_DETAIL, content = { navBackStackEntry, navController -> ProfileScreen( navController = navController, id = navBackStackEntry.arguments?.getString("id").orEmpty() ) } ) )

Each Screen object specifies:

  • route: The corresponding route from the ScreenRoute enum.
  • content: The composable function responsible for rendering the screen’s UI.
  1. Optional: Bottom Navigation Integration

We’ve provided a pre-built BottomNavigationBar composable for easy integration:

Scaffold( bottomBar = { BottomNavigationBar( navController = navController ) } )

You can either manually define navigation items or leverage the BottomNavigationItem enum for a centralized approach.

More information on Compose Navigation can be found in the official documentation.