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

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

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

            android:ellipsize="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的字体。

你可能感兴趣的:(Android)