4.2 Implementation of the Bottom Navigation Bar

The bottom navigation bar is one of the most common type of navigation system in Android apps. Implementing it in Jetpack Compose does require a bit of diligence though. This textbook page should help walk you through the process nicely and explain some of the code in more detail than the demo.

Much of this tutorial can also be applied for basic Compose navigation even if you aren't using a navbar, so if that is your use case, feel free to read on!

Step 0: Dependencies:

To start, you'll need to add the following in your libs.versions.toml file to specify the library versions. Under [libraries] and [plugins], add the corresponding lines:

libs.versions.toml
[libraries]
# ...
androidx-compose-navigation = { group = "androidx.navigation", name = "navigation-compose", version="2.8.0-beta06"}
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version = "1.6.3" }

[plugins]
# ...
jetbrains-kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }

Then, in build.gradle file, add the following lines:

build.gradle (Module: app)
plugins {
    // ...
    alias(libs.plugins.jetbrains.kotlin.serialization)
}

dependencies {
    // ... 
    implementation(libs.androidx.compose.navigation)
    implementation(libs.kotlinx.serialization.json)
}

Step 1: Creating the Screen sealed class

When using type-safe navigation with compose, it's helpful to have one parent sealed class called Screen that we can use in our app. This way we instantly know which data classes are screens and which ones represent data within our app. Create a sealed class, and create a couple subclasses that extend it with some routes you want your app to have. It could be a good idea to putt this class in its own file.

We will annotate each of these classes with @Serializable, since we want Compose navigation to be able to pass these screen objects between activities, so we need to let the compiler know that these can be converted to strings.

We're also going to make ProfileScreen a data class, this will allow us to pass arguments to the screen. We specify a mandatory userId argument here, so whenever someone loads the ProfileScreen, they need to pass a userId. If you want to pass a custom object between screens, I recommend checking out this video (although it's rare that you would actually need to do this).

Screen.kt
@Serializable
sealed class Screen {
    @Serializable
    data object HomeScreen : Screen()

    @Serializable
    data object SettingsScreen : Screen()

    @Serializable
    data class ProfileScreen(val userId: String) : Screen()
    // ...
}

Step 2: Initializing a NavHost

The NavHost will select the correct screen to display based on the current route in its navController. It will also specify which route the app starts at. Let's initialize a navController and the corresponding NavHost . You may notice that we are using a Scaffold here. A Scaffold is a layout composable that helps us arrange a bottom bar and main content, so this is only for if you want to use bottom navigation. Also note that we wrapped our content in a Box that uses innerPadding. This is just to make sure that the content is not behind the bottomBar composable.

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // ...
         
        setContent {
            FromScratchNavigationTheme {
                val navController = rememberNavController()

                Scaffold(modifier = Modifier.fillMaxSize(), bottomBar = {
                    // TODO we will create our bottom navigation bar here
                }) { innerPadding ->
                    Box(modifier = Modifier.padding(innerPadding)) {
                        NavHost(
                            navController = navController,
                            startDestination = Screen.HomeScreen
                        ) {
                            composable<Screen.HomeScreen> {
                                Text(text = "HOME: add your screen here")
                            }
                            composable<Screen.SettingsScreen> {
                                Text(text = "SETTINGS: add your screen here")
                            }
                            composable<Screen.ProfileScreen> {
                                Text(text = "PROFILE: add your screen here")
                            }
                        }
                    }
                }
            }
        }
    }
}

Step 3: Defining a bottom tab

Each app could have its own notion of a "bottom tab", depending on how you want it to look and what information you need to store. For this demo, I'm going to assume that we want each bottom tab to have an icon, label, and screen. So I am going to represent this with a data class.

data class NavItem(
    val screen: Screen,
    val label: String,
    val icon: ImageVector
)

Then, we need to specify the data of our tabs with a list. This should be held in state in the ViewModel, but for now we can just store the list of tabs in the onCreate method. Here are the tabs I made for this tutorial:

val tabs = listOf(
            NavItem(
                label = "Home",
                icon = Icons.Filled.Home,
                screen = Screen.HomeScreen,
            ),
            NavItem(
                label = "Settings",
                icon = Icons.Filled.Settings,
                screen = Screen.SettingsScreen,
            ),
            NavItem(
                label = "Profile",
                icon = Icons.Filled.Person,
                screen = Screen.ProfileScreen,
            )
        )

Step 4: Adding the navigation bar

To create the navigation bar, we're going to use the bottomBar parameter of the Scaffold layout and pass in a NavigationBar composable. We map our list of tabs to actual composable functions that display the tabs. We can use NavigationBarItem for this. The updated code now looks as follows:

Scaffold(modifier = Modifier.fillMaxSize(), bottomBar = {
            NavigationBar {
                tabs.map {
                    NavigationBarItem(
                        selected = false,  // TODO
                        onClick = { navController.navigate(it.screen) },
                        icon = { Icon(imageVector = it.icon, contentDescription = null) },
                        label = { Text(text = it.label) }
                    )
                }
            }
        }
    )

However, we still have one problem. How do we know if a NavigationBarItem is selected? We can store the index of the selected navigation bar item in a rememberSavable (a value that is remembered across configuration changes). Then we can change our call from map to mapIndexed, and compare the index of the current item with the index of the selected item. Note that we also abstracted away the STARTING_INDEX value for easier reuse in the future. The implementation looks like this:

var selectedTabIndex by rememberSaveable {
    mutableIntStateOf(STARTING_INDEX)  
}

Scaffold(modifier = Modifier.fillMaxSize(), bottomBar = {
    NavigationBar {
        tabs.mapIndexed { index, item ->
            NavigationBarItem(
                selected = index == selectedTabIndex,
                onClick = {
                    // Make sure to add this line so we update selected tab index
                    // when the user navigates to a tab!
                    selectedTabIndex = index
                    navController.navigate(item.screen)
                },
                icon = { Icon(imageVector = item.icon, contentDescription = null) },
                label = { Text(text = item.label) }
            )
        }
    }
})

We still have one last step however. If you run your app now, you may notice that the starting screen is misaligned with the selected tab on the bottom navigation bar. So to resolve this, we want to change the startDestination of the NavHost to tabs[STARTING_INDEX].screen so it aligns with the selected tab on our bottom navigation bar. So now NavHost should look like:

NavHost(
    navController = navController,
    startDestination = Screen.HomeScreen
) {
    // ...
}

Step 5: Future Customization

Congrats, you implemented a bottom navigation bar in Jetpack Compose! Here are some tips to help you with general navigation skills:

Let's say I wanted to navigate to a ProfileDetails screen from my Profile screen, and I wanted my Profile screen to receive an id.

It's recommended that we pass the navigation action in a lambda to ProfileScreen, instead of giving it access to the entire navController. The reason is, if we put navController as a parameter for ProfileScreen, then that makes ProfileScreen difficult to test. If we wanted to try to test ProfileScreen in isolation, we'd need to provide a mock navigator to it, instead of just being able to provide an empty lambda for navigation to other screens. So the code looks like this:

NavHost(
    navController = navController,
    startDestination = navigationItems[STARTING_INDEX].route
) {
    composable<Screen.Home> {
        HomeScreen(navigateToProfileDetails = { id ->
            navController.navigate(Screen.ProfileDetails(id))
        })
    }
    // ...
}

Receiving navigation arguments

To receive navigation arguments on a certain screen, we want to use the NavBackStackEntry. The composable function in NavHost actually takes a parameter of type @Composable() ((NavBackStackEntry) -> Unit), meaning that inside the composable function, the parameter we have access to is the NavBackStackEntry. This is more easily understood through example:

NavHost(
    navController = navController,
    startDestination = navigationItems[STARTING_INDEX].route
) {
    composable<Screen.ProfileDetails> { navBackStackEntry ->
        val profileId = navBackStackEntry.toRoute<Screen.ProfileDetails>().profileId
        ProfileDetails(profileId)
    }
    // ...
}

Whenever NavHost maps the current navigation destination to a composable, that composable provides navBackStackEntry. We can then get the arguments that we're looking for by using the toRoute function, which takes the back stack entry, and converts it to an instance of our Screen.ProfileDetails data class. We can access the fields of this data class, so that includes profileId. Then we are able to pass this as a parameter to our hypothetical ProfileDetails screen.

Last updated