Search code examples
androidkotlinandroid-jetpack-compose

How can I add a vertical divider in ListItem?


How can I add a vertical divider between headlineContent and trailingContent in ListItem() with Jetpack Compose that looks like this:


Solution

  • With material3, you should use a VerticalDivider:

    import androidx.compose.material3.VerticalDivider
    
    @Composable
    fun SettingsRow() {
        var checked by rememberSaveable { mutableStateOf(false) }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(
                modifier = Modifier.weight(1f)
            ) {
                Text(text = "Wireless debugging", style = MaterialTheme.typography.headlineSmall)
                Text(text = "Debug mode when Wi-Fi is connected")
            }
            VerticalDivider(
                modifier = Modifier
                    .height(32.dp)
                    .padding(horizontal = 24.dp)
            )
            Switch(
                checked = checked,
                onCheckedChange = {
                    checked = it
                }
            )
        }
    }
    

    Output:

    Screenshot


    If you are using Material Design 2, you can make the Divider vertical as follows:

    Divider(
        color = Color.Black,
        modifier = Modifier.height(32.dp).width(1.dp)
    )
    

    If you want to make the Divider fill the whole height of the Row instead of the fixed height of 32.dp, use

    Row(
        modifier = modifier.height(IntrinsicSize.Min)
    ) {
    
        // Texts ...
        Divider(
            color = Color.Black,
            modifier = Modifier.fillMaxHeight().width(1.dp)
        )
        // Switch ...
    }