Create Vertical Divider Jetpack Compose

Viewed 9657

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?

3 Answers

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)
    .fillMaxWidth()
    .background(Color.Yellow)) {

        Text("First Text")

        Divider(
            color = Color.Red,
            modifier = Modifier
                .fillMaxHeight()
                .width(1.dp)
        )

        Text("Second text")
}

enter image description here

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

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

Related