I have an address text consisting of a street part...
# compose
l
I have an address text consisting of a street part, a comma and zip code/city part (with possible city districts).
Some street 1, 10000 München / Altstadt-Nord
I want to display it in one line, if it fits. However when it doesn't fit, I want that it breaks at the first comma, so that e.g. the zip code is not in the "street" line, and separate from the city line. I don't want to use non-breaking spaces, because then if the zip code/city part is also longer than one line, it gets broken in the middle of the words.
I guess I have to somehow measure before displaying, if the text is going to fit in one line and then decide it it should be one or two lines.
m
You can use TextMeasurer
l
Thanks
It always returns 1 line, even if the text is displayed in multiple lines:
Copy code
val textMeasurer = rememberTextMeasurer()

            val lineCount = textMeasurer.measure(
                text = formattedAddress,
                style = MaterialTheme.typography.bodyLarge,
            ).lineCount
I suppose
textMeasurer.measure()
also needs constraints from the layout.
d
Yep by default the maxWidth constraint is Infinity which will always give you 1 line
l
I'm trying to measure the parent width in
onGloballyPositioned()
but it also returns infinity, I guess it's too early
d
If you're set on using TextMeasurer and something simpler like https://developer.android.com/develop/ui/compose/text/style-paragraph#insert-line doesn't work, you could wrap your text in
BoxWithConstraints
however beware that this uses SubcomposeLayout so there's a cost to it
m
The simplest solution is to wrap whatever you need in
BoxWithConstraints
.
BoxWithConstraintsScope
has
constraints
property available.
But, yeah. As mentioned above there is a cost associated with subcomposition.
Though I probably wouldn't worry too much about it in your case
d
I'd worry if this is displaying tons of addresses in a LazyColumn (i.e. for address lookup feature)
l
This is a LazyColumn with up to a few thousand addresses...
m
Even that might not be a big problem due to laziness. It doesn't render all of them at once.
👍 1
It's best to test it and see if performance issues occur.
l
Hmm, suddenly
onGloballyPositioned()
started delivering the correct width.
Looks like
onGloballyPositioned()
not working was an Android Studio preview problem.