Search code examples
androidandroid-jetpackandroid-jetpack-compose

Jetpack compose. Center icon in ListItem


How to properly center an icon in ListItem?

Column {
    ListItem(
        icon = {
            Icon(
                imageVector = Icons.Outlined.Delete,
                contentDescription = null
            )
        },
        secondaryText = { Text("secondaryText") },
        text = { Text("text") }
    )
    Divider()
}

gives this result

enter image description here

ListItem implementation uses explicit Box(contentAlignment = Alignment.TopStart) to place the icon. Mmm...why?

I can, of course, use paddings or create a custom ListItem, but there must be a standard solution.


Solution

  • According to M2 specs, you can add the Modifier.size(40.dp) to the Icon

    Something like:

        ListItem(
            text = { Text("Two line list item with 40x40 icon") },
            secondaryText = { Text("Secondary text") },
            icon = {
                Icon(
                    Icons.Filled.Favorite,
                    contentDescription = null,
                    modifier = Modifier.size(40.dp)
                )
            }
        )
    

    enter image description here

    The ListItem follows the material guidelines:

    enter image description here


    With M3 it is not needed since the leadingContent has a default contentAlignment = Alignment.Center:

    Column {
        ListItem(
            leadingContent = {
                Icon(
                    imageVector = Icons.Outlined.Delete,
                    contentDescription = null
                )
            },
            supportingText = { Text("Supporting Text") },
            headlineText = { Text("Headline Text") }
        )
        Divider()
    }
    

    enter image description here

    Specs:

    enter image description here