我可以限制 TextView 的字符数吗?

我现在有一个 TextView 元素的 ListView。每个 TextView 元素显示一个文本(文本长度从12个单词到100 + 不等)。我想让这些 TextView 显示文本的一部分(比如说20个单词或大约170个字符)。

如何将 TextView 限制为固定数量的字符?

97487 次浏览

you can extend the TextView class and overwrite the setText() function. In this function you check for text length or word cound.

Here is an example. I limit the sizewith the maxLength attribute, limit it to a single line with maxLines attribute, then use the ellipsize=end to add a "..." automatically to the end of any line that has been cut-off.

<TextView
android:id="@+id/secondLineTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:maxLength="10"
android:ellipsize="end"/>

Use below code in TextView

 android:maxLength="65"

Enjoy...

If your not interested in xml solutions maybe you can do this:

String s="Hello world";
Textview someTextView;
someTextView.setText(getSafeSubstring(s, 5));
//the text of someTextView will be Hello

...

public String getSafeSubstring(String s, int maxLength){
if(!TextUtils.isEmpty(s)){
if(s.length() >= maxLength){
return s.substring(0, maxLength);
}
}
return s;
}

As mentioned in https://stackoverflow.com/a/6165470/1818089 & https://stackoverflow.com/a/6239007/1818089, using

android:minEms="2"

should be enough to achieve the goal stated above.

I did this using the maxEms attribute.

 <TextView
android:ellipsize="end"
android:maxEms="10"/>

Programmatic Kotlin.

Cut off the start of the text:

 val maxChars = 10000
if (helloWorldTextView.text.length > maxChars) {
helloWorldTextView.text = helloWorldTextView.text.takeLast(maxChars)
}

Cut off the end of the text:

 val maxChars = 10000
if (helloWorldTextView.text.length > maxChars) {
helloWorldTextView.text = helloWorldTextView.text.take(maxChars)
}

I am sharing an example where I have set maxLength=1 i.e. limit it to a single line with maxLines attribute, then use the ellipsize=end to add a "..." automatically to the end of any line that has been cut-off.

Please Note: layout_width which is 120dp i.e. after 120dp any text exceeding will triggrer "ellipsize=end" property

paste the below code directly to check.

<TextView
android:layout_width="120dp"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:maxLength="40"
android:text="Can I limit TextView's number of characters?"
android:textColor="@color/black"
android:textSize="12sp"
android:textStyle="bold" />

.