I have a `Text` that shows a value that changes wh...
# compose
a
I have a
Text
that shows a value that changes while it is displayed - sometimes it’s is short, other times long, and the longest value that can be displayed is known. The
Text
is part of a
Row
where another element has
weight(1f)
. I would like to have this
Text
measured with the longest value, so that the layout doesn’t change when the value changes. Is there a clean (no hacks like adding a transparent
Text
with the longest value) way to do this?
s
This article https://medium.com/androiddevelopers/problem-solving-in-compose-text-d1dd1feafe4a has some approaches one could take. And tbh I would in fact go with a Box where you lay out the text with the max letters and simply not place, only lay it out, (basically this), even though I know you said you don't want that 😅
a
That’s the solution I expect I will need; I was hoping to avoid it, though. Seems like a common functionality that should be available in the library.
s
Yeah maybe it should be. Because doing the alpha approach is something many people do but I think that doesn't play well with semantics staying around. I think that the "no placement" solution is better at that.
But do check out the other approaches, maybe one of those suits you just as well here?
a
They seem to have gone with the option of placing another
Text
, which I imagine can cause all sorts of problems. Some off the top of my head: 1. Screen readers will read both texts. Can be worked around by providing a custom semantics on the other text. 2. If you place this in a
SelectionContainer
, god knows what you will end up copying.
yes, exactly
The correct option is #4, I feel
A custom layout that measures the desired text
s
I would expect screen readers and SelectionContainer to not read anything if you do
layout(width = width, height = height) {}
since nothing is placed at all, is that not the case?
a
If you don’t place it, sure. I was talking about option #1, placing two `Text`s, which the article says they ended up using.
s
Oh yeah, but I'd personally go with #1 + add the aforementioned
.withoutPlacement()
which imo is the best of both worlds.
a
Ah, I didn’t see your 2nd link
s
No problem 😊
a
Yeah, that’s a reasonable hack.
z
I would use a TextMeasurer to calculate the max size
a
Seems like a useful feature to have in the library.
probably a common use-case
z
Feel free to file a feature request
There’s some edge cases though, considering material vs non material, inline content, etc.
a
I was thinking something like
Copy code
Text(
    text: String,
    measuredText: String = text
    ...
)
z
feel free to file a feature request. This feels like a pretty niche thing to give such a front-and-center API though.