BottomBar and TopBar with Jetpack compose

yadunath narayanan
2 min readSep 7, 2021

TopBar and BottomBar are one of the common feature most android apps have.So when it comes to jetpack compose we have a very easy way to implement topbar and bottombar programatically .

First we will discuss about topbar

Create a kotlin file called TopBar and create a compose function like below

@Composable
fun topBar(){
TopAppBar(title ={ Text(
text = "MyComposeApp",
style = MaterialTheme.typography.h6,
textAlign = TextAlign.Center
)})
}

This will create a topbar ui for your application.To add this to your main Ui compose function add below line to your Mainactivity compose function theme.

Scaffold(
topBar = { topBar() }
) {
NavHost(navController = navController, startDestination ="home" ) {
composable("home"){
}

So now if you run the app you will find a topbar with title as MyComposeApp.

Next step is to create the bottombar

Create a kotlin file called BottomBarItems.kt

and add the following compose function

sealed class BottomBarItems(var route:String,var icon:Int,var title:String){
object Home :BottomBarItems("home", R.drawable.home_icon,"Home")
object Search :BottomBarItems("search", R.drawable.search_icon,"Search")
object Profile :BottomBarItems("profile", R.drawable.profile_icon,"Profile")
}

so here we created three bottombar items home,search and profile.We have added titles and icons and route to each item.

Now we need to add this items to our bottombar

@Composable
fun bottomBar(navController: NavHostController){
val items = listOf(
BottomBarItems.Home,
BottomBarItems.Search,
BottomBarItems.Profile
)
BottomNavigation {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentRoute = navBackStackEntry?.destination?.route
items.forEach { item ->
BottomNavigationItem(
icon = { Icon(painter = painterResource(id =item.icon) , contentDescription =null ) },
label = { Text(text = item.title) },
onClick = {
navController.navigate(item.route)
},
selected = currentRoute == "home")
}
}
}

So to add these items to bottombar,we created a list called items and added three items to the list.

Then Called the BottomNavitgation with BottomNavigationItem(which is taking input from items list).

Once this is done we need to add this bottombar to our main ui like topbar,

var navController = rememberNavController()
Scaffold
(
topBar = { topBar() },
bottomBar = { bottomBar(navController = navController) })
{
NavHost(navController = navController, startDestination ="home") {
composable("home"){
}

That’s it .Now we will be able to see the topbar and bottom bar with 3 items

Happy Reading …. Happy Coding…

--

--

yadunath narayanan

Passionate android developer working with android mobile and androidTv