Is there a way to tell a Text
composable to be as wide as e.g. 2 characters no matter what the provided text is?
I want to have a row with weights and some fixed size cells but I do want the fixed size cells to have a width that's exactly as large as it needs to be to contain n characters of the provided font...
You can use the TextMeasurer
to measure a text and set a width according the first 2 characters (or with a fixed text with 2 characters).
Something like:
val textMeasurer = rememberTextMeasurer()
val textLayoutResult: TextLayoutResult =
textMeasurer.measure(
text = AnnotatedString(text.substring(0,2)), //you have to check if the length is <2
style = LocalTextStyle.current
)
val textSize = textLayoutResult.size
val density = LocalDensity.current
Text(
text = text,
modifier = Modifier
.width( with(density){textSize.width.toDp()} )
.background(Yellow), //it is not needed
maxLines = 1
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With