Java Android:TextView 自动截断并替换 String 的最后 3 个字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1666736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android: TextView automatically truncate and replace last 3 char of String
提问by znq
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.
如果 aString
比TextView
的宽度长,它会自动换行到下一行。我可以通过使用android:singleLine
(已弃用)或设置android:inputType="text"
. 我现在需要的是String
用“ ...”替换 my 的最后 3 个字符。由于我没有使用等宽字体,因此根据我的String
. 所以我想知道在 a 中获取字符串的最后 3 个字符TextView
并替换它们的最佳方法是什么。也许Android框架中已经实现了一些东西,因为这肯定是一个常见问题。
采纳答案by Nate
You should be able to use the "ellipsize" property of a text view:
您应该能够使用文本视图的“ellipsize”属性:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/text_mytext"
android:ellipsize="end"
android:maxLines="1"
/>
You may also need to apply gravity values to the layout too; I have sometimes seen "auto-stretching" views without them.
您可能还需要将重力值应用于布局;我有时会看到没有它们的“自动拉伸”视图。
回答by BonanzaDriver
Found an interesting work-a-round for this problem.
为这个问题找到了一个有趣的解决方法。
maxLines=1
ellipsize=end
scrollHorizontally=true
The trick is that last statement about horizontal scrolling .... check it out. It at least works on v2.2.
诀窍是关于水平滚动的最后一条声明......检查一下。它至少适用于 v2.2。
回答by xevser
Programmatically, you can use:
以编程方式,您可以使用:
TextView tx = new TextView(this);
tx.setTextSize(13);
tx.setGravity(Gravity.CENTER);
tx.setTop(90);
tx.setText("Long text here");
tx.setTextColor(Color.BLACK);
tx.setSingleLine(true);
tx.setEllipsize(TruncateAt.END);