How can I check if text is overflowed or not? I wa...
# compose
r
How can I check if text is overflowed or not? I want to show
See more/less
based on text displayed.
1
I know about setting maxLines to show/hide text, but I want to implement
See more/less
based on how text is displayed on screen. For example, maxLines is set to 2 by default. if text is only of 1 line, there shouldn't be any
See more/less
text.
z
you could probably use the text layout result, but that will only be available for the second frame. You might have to use one of the text APIs to measure the text yourself and predict if it will overflow.
h
would subcomposing be overkill for this?
z
Like, subcompose+measure the text, get the layout result, then subcompose the overlay? Is the text layout result available by then? If so, that seems reasonable.
r
I achieved it after some experiments. below is the code
Copy code
var isExpanded by rememberSaveable { mutableStateOf(false) }
var isOverflowed by rememberSaveable { mutableStateOf(false) }

Text(
     text = text,
     maxLines = if (isExpanded) 1000 else 2,
     onTextLayout = { isOverflowed = it.hasVisualOverflow },
     overflow = TextOverflow.Ellipsis,
)