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

mattinger

02/08/2022, 5:43 PM
Does anyone know if there’s a good way to measure the number of rendered lines of text in a Text element? Our UX is asking us to change the alignment of an icon that sits to the left of the text in a row (nothing that would change the text itself to resize or reposition) based on how many lines of text are rendered. In the XML world, you could use things like FontMetrics and what not to do this. Not sure about compose.
a

Albert Chang

02/08/2022, 6:24 PM
See the
onTextLayout
parameter of
Text
. Note that you need a custom layout to place the icon according to the line count of the text.
m

mattinger

02/08/2022, 6:40 PM
Thanks @Albert Chang That works for me, but i’m then some state objects to hold these counts:
Copy code
val numberOfHeadlineLines = remember { mutableStateOf(0) }
    val numberOfBodyLines = remember { mutableStateOf(0) }
    val iconAlignment = derivedStateOf {
        if (numberOfBodyLines.value + numberOfHeadlineLines.value >= 3) {
            <http://Alignment.Top|Alignment.Top>
        } else {
            Alignment.CenterVertically
        }
    }
This is causes the icon to start center aligned and then jump to the top. It makes sense that it does since it’s state and it’s going to lay things out, display it, and then recompose when the value of iconAlignment is set. I’m not sure i can do anything about that, and it’s a red flag i’ve given to our UX about this requirement
a

Albert Chang

02/08/2022, 7:05 PM
Yeah that's exactly why you need a custom layout.
2 Views