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

Peter

03/11/2024, 9:53 AM
How can I make text my button to match text width? 👀 If display/font scale is increased, text breaks to new line, but button width doesn't seem to match text width. It has unnecessary width. If I use
IntrinsicSize.Min
text will always break, which I don't want.
Copy code
Button(onClick = onClick) {
    Text(text = "Add to schedule")
}
s

Stylianos Gakis

03/11/2024, 2:04 PM
It should already just match the text size if you do nothing and the button has room to grow itself no?
z

Zach Klippenstein (he/him) [MOD]

03/11/2024, 4:13 PM
Like Stylianos said, it should grow horizontally first until it runs out of space.
If you are using intrinsics, you’d want to use Max not Min
p

Peter

03/11/2024, 4:15 PM
It does grow horizontally. And it also ran out of space. I have another element next to it, that prevents it from growing further horizontally.
I guess I didn't provide the best screenshots 😅
s

Stylianos Gakis

03/11/2024, 4:21 PM
I have another element next to it, that prevents it from growing further horizontally. Then it looks like that is your issue in the first place. It really depends on what your requirements are for this scenario. We use this https://github.com/HedvigInsurance/android/blob/96ae640dc65b1c7726c983ddfeae60dab1[…]ig/android/core/ui/text/HorizontalItemsWithMaximumSpaceTaken.kt for when we have two items horizontally that we don’t want one to “gobble” the other one but to share the space fairly, just as an example. It’s surprisingly often what people are looking for so I keep linking it in this channel 😄 Original solution was proposed here
p

Peter

03/11/2024, 4:45 PM
Interesting solution, thanks. In my case the button already has more than 1/2 of the screen width, so I guess it already has a fair amount of space. I was just wondering how to trim unnecessary width of the button, in the case when text wraps.
s

Stylianos Gakis

03/11/2024, 4:49 PM
Oh hm that one I am not so sure about.
z

Zach Klippenstein (he/him) [MOD]

03/11/2024, 6:13 PM
Oh, ok. We have a bug open for that, I thought it had been fixed recently but I’ll double check
What version of compose are you using?
p

Peter

03/11/2024, 6:23 PM
Not the latest. We're a bit behind atm: 2023.10.01
s

Stylianos Gakis

03/11/2024, 6:28 PM
Try making a simple new project with the latest to see if you experience the same thing perhaps
s

Son Phan

03/12/2024, 7:46 AM
This is likely a bug of Compose's Text. Just FYI, this bug also happens with tranditional View's TextView This answer solves it https://stackoverflow.com/questions/69941390/how-to-make-multi-line-text-wrap-width-in-compose/69947555#69947555 (Slightly worse performance, btw)
z

Zach Klippenstein (he/him) [MOD]

03/12/2024, 5:01 PM
y

youssef

03/19/2024, 7:59 AM
just use softWrap = false and maxLine = 1
2 Views