TextView的省略号(elipsized属性)工作原理

TextView在单行状态下,通过android:ellipsize属性可以实现文字截断并添加省略号。Android使用的是一个包含三个点的特殊字符作为省略号,而非三个独立的点。在截断过程中,字符串长度保持不变,被替换的字符由省略号和Unicode字符'ZERO WIDTH NO-BREAK SPACE'填充,确保不占用屏幕空间。如果自定义字体不支持这个Unicode字符,可能会出现显示问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原帖链接:http://stackoverflow.com/questions/6492074/why-does-textview-in-single-line-elipsized-with-end-show-boxes

有人在stackoverflow上提问,说单行状态下的TextView,设置行末省略号属性:

            android:ellipsize="end"             
实测却在省略号后面却出现了奇怪的方框:

TextView shown box at end

最佳回答:

Android's TextView class has the built-in ability to "ellipsize" text, truncating it and adding an ellipsis if the text is longer than the available space. You can use this via the android:ellipsize attribute, for example. This works fairly well, at least for single-line text. The ellipsis that Android uses is not three periods. Rather it uses an actual ellipsis character, where the three dots are contained in a single glyph. Hence, any font that you use that you also use the "ellipsizing" feature will need the ellipsis glyph.

Beyond that, though, Android pads out the string that gets rendered on-screen, such that the length (in characters) is the same before and after "ellipsizing". To make this work, Android replaces one character with the ellipsis, and replaces all other removed characters with the Unicode character 'ZERO WIDTH NO-BREAK SPACE' (U+FEFF). This means the "extra" characters after the ellipsis do not take up any visible space on screen, yet they can be part of the string.

However, this means any custom fonts you use for TextView widgets that you use with android:ellipsize must also support this special Unicode character. Not all fonts do, and you will get artifacts in the on-screen representation of your shortened strings if your font lacks this character (e.g., rogue X's appear at the end of the line).

大致意思是,TextView的末尾省略号是把文本的一个字符替换为省略号(不是三个点,而是真正的省略号…,编号U+2026),并且将剩下需要删除的字符 替换为一个零宽无间断间隔(U+FEFF),这个符号大家应该很熟悉,Windows记事本把它作为“万恶的”BOM放在文本文件头部。它并不占据屏幕显示空间。 问题是类似题主所用的某些自定义字体并不支持这个字符,所以显示出来就是一个方框了。解决办法就是用系统自带的字体,或者用支持U+FEFF的字体。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值