动态省略号支持Android自动调整TextViews的大小 [英] Dynamic ellipsis support for Android autosizing TextViews
问题描述
新的自动调整TextView的大小很棒,但是似乎缺少了一个基本的东西:省略号.
The new Autosizing TextViews are pretty awesome, but it seems a fundamental thing is missing: ellipses.
添加椭圆仍然需要定义maxLines
属性,但是如果我希望能够根据文本视图边界动态调整文本大小,我还希望能够在需要时动态添加椭圆.现在,如果即使最小尺寸也无法容纳文本,则会被裁剪掉.
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?
推荐答案
到目前为止,我想到的最好的解决方案是在运行时以编程方式将maxLines
设置为适当的值.这样的事情就可以完成工作:
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
}
请注意,这取决于Android KTX(但也可以通过常规OnPreDrawListener
轻松实现).
Be aware that this depends on Android KTX (but can also be easily achieved with a regular OnPreDrawListener
).
然后,我们可以简单地从任何要获取动态省略号的TextView
中调用此扩展名.
Then we can simply call this extension from any TextView
we want to get the dynamic ellipsis.
textView.setMaxLinesForEllipsizing()
但是,如果文本更改,则可能有必要再次调用它.因此,也可以通过将逻辑移到自定义TextView
并覆盖其中的onTextChanged()
来获得更完整(更复杂)的解决方案.
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.
这篇关于动态省略号支持Android自动调整TextViews的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!