https://kotlinlang.org logo
#compose
Title
# compose
j

Jeff

09/10/2021, 10:16 AM
I can't seem to get the text to the middle of the circle shape. Code in thread 🧵
Copy code
Box(contentAlignment = Alignment.Center,
    modifier = Modifier
        .background(colorResource(id = R.color.green_700), shape = CircleShape)
        .layout { measurable, constraints ->
            // Measure the composable
            val placeable = measurable.measure(constraints)

            //get the current max dimension to assign width=height
            val currentHeight = placeable.height
            var heightCircle = currentHeight
            if (placeable.width > heightCircle)
                heightCircle = placeable.width

            //assign the dimension and the center position
            layout(heightCircle, heightCircle) {
                // Where the composable gets placed
                placeable.placeRelative(
                    0,
                    (heightCircle - currentHeight) / 2
                )
            }
        }) {

    Text(
        modifier = Modifier
            .padding(1.dp)
            .align(Alignment.Center)
            .defaultMinSize(4.dp),
        text = chatUser.user.unRead.toString(),
        textAlign = TextAlign.Center,
        style = MaterialTheme.typography.caption,
        color = Color.White,
    )
}
a

Albert Chang

09/10/2021, 10:28 AM
You are placing the text with an x of 0 so it'll always be at the start.
j

Jeff

09/10/2021, 10:29 AM
How do I place the text in the middle
a

Albert Chang

09/10/2021, 10:33 AM
Copy code
placeable.place(
    (heightCircle - placeable.width) / 2,
    (heightCircle - currentHeight) / 2
)
PS. it's a good habit to use variable names that describe their usage exactly.
j

Jeff

09/10/2021, 11:01 AM
Thanks it's working
t

Tobias Suchalla

09/10/2021, 11:54 AM
BTW, you can do this without a custom layout (you might want to tweak
size
and
fontSize
):
Copy code
val size = 24.dp
val fontSize = 12.sp

Box(
    modifier = Modifier
        .background(colorResource(id = R.color.green_700), CircleShape)
        .size(size),
    contentAlignment = Alignment.Center
) {
    Text(
        modifier = Modifier.padding(end = 1.dp), // otherwise slightly off-center
        text = chatUser.user.unRead.toString(),
        fontSize = fontSize,
        style = MaterialTheme.typography.caption,
        color = Color.White,
    )
}
☝️ 2
☝🏻 1
a

Albert Chang

09/10/2021, 1:00 PM
I don't think hardcoding text size is a good idea as it can easily break your UI in some specific configurations (different text scales, different fonts, etc). There's no point doing so as layouts are quite lightweight in Compose UI.
c

Chris Sinco [G]

09/13/2021, 6:51 PM
@Jeff is there a reason you are using a custom layout versus using
contentAlignment
in your
Box
?