我可以限制 TextView 的字符数吗?
我现在拥有的是 TextView 元素的 ListView。每个 TextView 元素显示一个文本(文本长度从 12 个单词到 100+ 不等)。我想要的是让这些 TextView 显示文本的一部分(假设 20 个单词或大约 170 个字符)。
如何将TextView限制为固定字符数?
What I have now is a ListView of TextView elements. each TextView element displays a text (the text length varies from 12 words to 100+). What I want is to make these TextViews display a portion of the text (let's say 20 word or roughly 170 chars).
How to limit the TextView to a fixed number of characters?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(10)
这是一个例子。我使用 maxLength 属性限制大小,使用 maxLines 属性将其限制为单行,然后使用 ellipsize=end 自动将“...”添加到已被截断的任何行的末尾。
Here is an example. I limit the sizewith the maxLength attribute, limit it to a single line with maxLines attribute, then use the ellipsize=end to add a "..." automatically to the end of any line that has been cut-off.
如果您对 xml 解决方案不感兴趣,也许您可以这样做:
...
If your not interested in xml solutions maybe you can do this:
...
在 TextView 中使用以下代码
享受...
Use below code in TextView
Enjoy...
我使用 maxEms 属性来完成此操作。
I did this using the
maxEms
attribute.我正在分享一个示例,其中我设置了 maxLength=1 即将其限制为具有 maxLines 属性的单行,然后使用 ellipsize=end 自动将“...”添加到已被截断的任何行的末尾。
直接粘贴下面的代码进行检查。
。
I am sharing an example where I have set maxLength=1 i.e. limit it to a single line with maxLines attribute, then use the ellipsize=end to add a "..." automatically to the end of any line that has been cut-off.
paste the below code directly to check.
.
您可以使用 TextView 类的 setEllipsize 方法
http://developer.android .com/reference/android/widget/TextView.html#setEllipsize(android.text.TextUtils.TruncateAt)
使用 TextUtil 类的常量添加暂停点
http://developer.android.com/reference/android/text/TextUtils .TruncateAt.html
You can use setEllipsize method of TextView class
http://developer.android.com/reference/android/widget/TextView.html#setEllipsize(android.text.TextUtils.TruncateAt)
With the constants of TextUtil class for added the suspension points
http://developer.android.com/reference/android/text/TextUtils.TruncateAt.html
程序化 Kotlin。
截断文本的开头:
截断文本的结尾:
Programmatic Kotlin.
Cut off the start of the text:
Cut off the end of the text:
这是正确的解决方案。请记住,将宽度设置为 WRAP CONTENT。 ems 不是基于 Max Charater 的。 EMS 基于宽度。如果 ems 值宽度超过文本长度,则自动 (...) 将添加到 textview 的最后。
Here is the correct Solution. Keep remember, to set width to WRAP CONTENT. and ems is not based on Max Charater. EMS based on width. If ems value width will exceed the text length, then automatically (...) will be added at last of textview.
正如 https://stackoverflow.com/a/6165470/1818089 中提到的https://stackoverflow.com/a/6239007/1818089,使用
应该足以实现上述目标。
As mentioned in https://stackoverflow.com/a/6165470/1818089 & https://stackoverflow.com/a/6239007/1818089, using
should be enough to achieve the goal stated above.
您可以扩展 TextView 类并覆盖 setText() 函数。
在此功能中,您可以检查文本长度或单词数量。
you can extend the TextView class and overwrite the setText() function.
In this function you check for text length or word cound.