4

Problem

The Composable androidx.compose.material.NavigationRail has in some documention an optional "centered" alignment. I cannot achieve this using Jetpack Compose.

The "old" XML attribute is app:menuGravity="center" according to this tutorial.

Things I tried without success

I tried to put the NavigationRail (a simple wrapper for the actual widget) in a Box with an alignment set:

Box(contentAlignment = Alignment.Center) {
    NavigationRail(
        selectedItem = selectedItem,
        onSelectItem = { selectedItem = it }
    )
}

and putting it directly into the original Composable:

NavigationRail(
    modifier = modifier.width(80.dp),
    backgroundColor = MaterialTheme.colors.surface
) {
   Box(contentAlignment = Alignment.Center) {
       for (item in NavigationItem.values()) {
      NavigationRailItem(
          selected = selectedItem == item,
          onClick = { onSelectItem.invoke(item) },
          icon = { Icon(item.icon, item.title) },
          alwaysShowLabel = true,
          selectedContentColor = MaterialTheme.colors.primaryVariant,
          unselectedContentColor = MaterialTheme.colors.primary,
          label = { Text(item.title, modifier = Modifier.padding(top = 8.dp)) }
      )
       }
   }
}

Screenhot (taken from the same site as the linked tutorial)

enter image description here

Tobonaut
  • 2,245
  • 2
  • 26
  • 39

1 Answers1

5

As suggested in the example to center the navigationRail's content you can use something like:

NavigationRail {
    Spacer(Modifier.weight(1f))
    items.forEachIndexed { index, item ->
        NavigationRailItem(
            //....
        )
    }
    Spacer(Modifier.weight(1f))
}

To achieve a Bottom alignment just use a Spacer:

NavigationRail {
    Spacer(Modifier.weight(1f))
    items.forEachIndexed { index, item ->
        NavigationRailItem(
            //....
        )
    }
}

enter image description here

Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841