Dynamic ellipsis support for Android autosizing TextViews

…衆ロ難τιáo~ 提交于 2020-06-25 09:02:10

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/46286469/dynamic-ellipsis-support-for-android-autosizing-textviews

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!