The new Autosizing TextViews are pretty awesome, but it seems a fundamental thing is missing: ellipses.
Adding ellipses still requires defining the maxLines
attribute, but if I want to be able to dynamically resize the text size according to the text view boundaries, I'd also like to be able to dynamically add ellipses when needed. Right now, if the text doesn't fit even with the minimum text size, it just gets cropped.
How could I add support for dynamic ellipses without giving up the new autosizing support?
The best solution I came up with so far was to programmatically set the maxLines
to the proper value on runtime. Something like this will get the job done:
fun TextView.setMaxLinesForEllipsizing() = doOnPreDraw {
val numberOfCompletelyVisibleLines = (measuredHeight - paddingTop - paddingBottom) / lineHeight
maxLines = numberOfCompletelyVisibleLines
}
Be aware that this depends on Android KTX (but can also be easily achieved with a regular OnPreDrawListener
).
Then we can simply call this extension from any TextView
we want to get the dynamic ellipsis.
textView.setMaxLinesForEllipsizing()
If the text changes it might be necessary to call it again, though. So it might also possible to reach a more complete (and complicated) solution by moving this logic to a custom TextView
and maybe overriding onTextChanged()
there.