在 Textview (...) 末尾添加点,点不显示

Adding the dots at the end of Textview (...) , dots not showing

每当文本(我从 Activity 以编程方式设置)长于 n 个字符时,我想切断并限制文本长度并添加 3 textview 末尾的点。 Text 在 xml 中最初设置为空(只是 ""),然后从 activity 开始设置。

这是我试过的方法:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text=""
    android:maxLength="10"
    android:ellipsize="end"
    android:maxLines="1"/>

这是它最终使用随机文本查找的方式,我将最大长度设置为 10 个字符:

我希望它看起来像 jrkfkgkglg... 因为文本是 jrkfkgkglggfgirng,但是最后没有添加点。有什么建议吗?

为了使其工作,您的宽度必须是 match_parent 或定义任何其他尺寸而不是 wrap_content

您告诉编辑文本的长度最多为 10 个字符,在您的屏幕截图中,您有一个具有该长度的字符串,因此如果您尝试向该字符串添加任何内容,它就不会被添加。

您可以删除 android:maxLength="10" 限制并以编程方式检查代码中的文本,如下所示:

if (yourText.length() > 10) {
    yourText = yourText.substring(0, 9); //get the first 10 chars
    textView.setText(yourText + "..."); //display 
} else {
    textView.setText(original string < 10chars);
}

为此,您必须删除属性

android:maxLines="1"

并添加新属性

android:singleLine="true"

此外,使您的文本视图宽度 match_parent。 当你添加它时它会正常工作,然后你不需要使用任何其他东西。