Create Vertical Divider Jetpack Compose

32.7k views Asked by At

How to create vertical dividers with Jetpack Compose? I try to use Spacer and Box to do it, but it doesn't show up at all. Here is what i tried:

Box(
    modifier = Modifier
        .fillMaxHeight()
        .width(2.dp)
        .background(color = Color.Black)
)

But that doesn't work at all. So how to do vertical divider in Jetpack Compose?

4

There are 4 answers

6
Gabriele Mariotti On BEST ANSWER

You can use the Divider composable with the width(xx.dp) modifier applying an intrinsic measurements to its parent container.

Something like:

Row(Modifier
    .height(IntrinsicSize.Min) //intrinsic measurements
    .fillMaxWidth()
    .background(Color.Yellow)
) {
        Text("First Text")

        Divider(
            color = Color.Red,
            modifier = Modifier
                .fillMaxHeight()  //fill the max height
                .width(1.dp)
        )

        Text("Second text")
}

enter image description here

As explained in the doc:

The Row composable's minIntrinsicHeight will be the maximum minIntrinsicHeight of its children. The Divider element's minIntrinsicHeight is 0 as it doesn't occupy space if no constraints are given; the TextField minIntrinsicHeight will be that of the content given a specific width. Therefore, the Row element's height constraint will be the max minIntrinsicHeight of the TextFields content. The Divider will then expand its height to the height constraint given by the Row.

0
Dafi On

composable has been a function rotate in Modifier object, so just rotate to 90 degree to your Divider compose

Divider(
    modifier = Modifier
               .padding(vertical = 16.dp)
               .rotate(90f),
    color = MaterialTheme.colorScheme.outline
)
0
Ashutosh Srivastava On

You can use BOX ,SPACER or DIVIDER to create a vertical divider

Row(modifier = Modifier.height(20.dp)) {
    Text("TEXT 1")
    Box(
        modifier = Modifier
            .fillMaxHeight()
            .width(2.dp)
            .background(Color.Red)
    )

    Spacer(
        modifier = Modifier
            .fillMaxHeight()
            .width(2.dp)
            .background(Color.Black)
    )

    Divider(color = Color.Blue, modifier = Modifier
        .fillMaxHeight()
        .width(2.dp))
    Text("TEXT 2")
}

Code result:

Code result

1
Nohus On

Here is a VerticalDivider Composable, which you can use the same way as the built-in Divider horizontal one.

@Composable
fun VerticalDivider(
    modifier: Modifier = Modifier,
    color: Color = MaterialTheme.colors.onSurface.copy(alpha = DividerAlpha),
    thickness: Dp = 1.dp
) {
    Box(
        modifier
            .fillMaxHeight()
            .width(thickness)
            .background(color = color)
    )
}

private const val DividerAlpha = 0.12f