Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic ellipsis support for Android autosizing TextViews

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?

like image 211
Fred Porciúncula Avatar asked Sep 18 '17 19:09

Fred Porciúncula


1 Answers

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.

like image 97
Fred Porciúncula Avatar answered Nov 06 '22 21:11

Fred Porciúncula