0

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...

prom85
  • 16,896
  • 17
  • 122
  • 242

1 Answers1

1

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
)
Gabriele Mariotti
  • 320,139
  • 94
  • 887
  • 841
  • That's my idea as well but in xml there was something like `ems`. With your suggestion I must know what the widest character in the current font is - otherwise the calculation is not accurate or I must add some buffer... – prom85 Mar 09 '23 at 12:29