Mehdi Haghgoo
Mehdi Haghgoo

Reputation: 3484

Cannot center-align items vertically in BottomNavigation

I'm trying to align items in the center vertically inside a bottom navigation in Compose. I'm not supplying any height to the modifiers. For some reason the items and the icons resist vertical center alignment. Here's what I have and then follows my code:

enter image description here

@Composable
fun BottomBarUi(backStackEntry: State<NavBackStackEntry?>, onNavigate: (String) -> Unit) {
    BottomNavigation(modifier = Modifier){
        val currDest = backStackEntry.value?.destination
        for (screen in LocalInfo.current.bottomBarItems){

            BottomNavigationItem(
                selected = currDest?.hierarchy?.any{it.route == screen.route} == true,
                onClick = {
                          onNavigate(screen.route)
                },
                icon = { Icon(painterResource(screen.iconId), contentDescription = screen.route, modifier = Modifier.align(Alignment.CenterVertically))},
                label = { Utils.getRouteLabel(screen.route)},
                modifier = Modifier
                    .padding(1.dp)
                    .align(Alignment.CenterVertically)
                    .weight(1f)
            )
        }
    }

}

@Preview
@Composable
fun PreviewBottomBarUi() {
    BottomBarUi(backStackEntry = rememberNavController().currentBackStackEntryAsState(), onNavigate = {})
}

Upvotes: 0

Views: 1045

Answers (1)

Johann
Johann

Reputation: 29877

If your icons have padding and you don't want to remove them, you can offset all the icons in the BottomNavigation by setting the offset modifier. Also remove your align modifier:

BottomNavigationItem(
     selected = currDest?.hierarchy?.any{it.route == screen.route} == true,
     onClick = {
                  onNavigate(screen.route)
     },
     icon = { Icon(painterResource(screen.iconId), contentDescription = screen.route, modifier = Modifier.align(Alignment.CenterVertically))},
     label = { Utils.getRouteLabel(screen.route)},
     modifier = Modifier
          .padding(1.dp)
          .offset(y = 10.dp)
          .weight(1f)
)

Another thing: it isn't clear why you are setting the label property since the image you've shown above doesn't display the image.

Upvotes: 1

Related Questions