androidandroid-jetpack-composealignment

How to vertically center row items in a column without using padding in Jetpack Compose?


I have built a business card with contact information aligned vertically centered that sits at the bottom of the app as shown in this Android Codelab.

I'm using horizontalArrangement = Arrangement.CerterHorizontally to align icons and text to the screen center, but row items don't get aligned with other row items vertically.

When I use weight on icon and text row items I get similar results but text gets too far away from icons.

I only get the desired result when using padding(start = ) to shrink the column so weighted items fill the screen bottom as shown below: (indicated code is commented)

@Composable
private fun ContactItem(icon: ImageVector, info: String) {
    Row(
//        modifier = Modifier.padding(start = 58.dp, bottom = 16.dp
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = Color(0xFF187545),
//            modifier = Modifier.weight(0.5f)
            )
        Text(
            text = info,
            fontSize = 20.sp,
            color = Color(0xFF154734),
//            modifier = Modifier.weight(2f)
        )
    }
}

If we use different android devices with other screen sizes we get undesirable results like contact info not being exactly centered.

Can we make this code more responsive to different screen sizes without using padding?


Solution

  • You can use another column for the contact items:

    Column(
      horizontalAlignment = Alignment.CenterHorizontally
    ) {
      // other items
    
      Column {
        ContactItem()
        ContactItem()
        ContactItem()
      }
    }
    

    with this, the second Column will wrap all of the contact items and will be centered inside of the parent Column. The individual contact items will be aligned to the start of the child column (implicitly), and thus their icons and texts will be aligned with each other.