安卓:TextView的自动截断并替换最后3字符字符串字符串、字符、TextView

由网友(把彼此站成两个世界⌒)分享简介:如果一个字符串长于的TextView 的宽度,自动折到下一行。单线(德precated)或通过设置安卓:inputType =文本。我现在需要的是什么,我替换字符串的最后3个字符 ... 。因为我不使用等宽字体,这将永远是不同,这取决于我在使用的字母串。所以,我不知道什么是得到了的TextView 字符串中的最后3个字...

如果一个字符串长于的TextView 的宽度,自动折到下一行。单线(德precated)或通过设置安卓:inputType =文本。我现在需要的是什么,我替换字符串的最后3个字符 ... 。因为我不使用等宽字体,这将永远是不同,这取决于我在使用的字母串。所以,我不知道什么是得到了的TextView 字符串中的最后3个字符,并取代它们的最好方法。也许有一些已经在Android框架内实现的,因为这必须是一个常见的​​问题。

If a String is longer than the TextView's width it automatically wraps onto the next line. I can avoid this by using android:singleLine (deprecated) or by setting android:inputType="text". What I need now is something that replaces the last 3 characters of my String with "...". Since I'm not using a monospace font this will always be different depending on the letters used in my String. So I'm wondering what's the best way to get the last 3 characters of a String in a TextView and replace them. Maybe there's already something implemented in the Android framework, since this must be a common problem.

推荐答案

您应该能够使用ellipsize文本视图的属性:

You should be able to use the "ellipsize" property of a text view:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/text_mytext"
    android:ellipsize="end"
    android:singleLine="true"
/>

您可能还需要重力值适用于布局也;我有时看到自动伸展没有他们的看法。

You may also need to apply gravity values to the layout too; I have sometimes seen "auto-stretching" views without them.