Can I limit the number of characters of a TextView?

Now I have a ListView element of TextView elements. each TextView element displays text (text length varies from 12 words to 100+). I want these TextViews to display part of the text (say 20 words or about 170 characters).

How to limit TextView to a fixed number of characters?

+50
android android-textview
Feb 05 2018-12-12T00:
source share
6 answers

Here is an example. I limit the maxLength attribute, limit it to one line with the maxLines attribute, then use ellipsize = end to add "..." automatically to the end of any line that has been disabled.

<TextView android:id="@+id/secondLineTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:maxLines="1" android:maxLength="10" android:ellipsize="end"/> 
+110
Feb 05 2018-12-12T00:
source share

If you are not interested in xml solutions, 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; } 
+4
Sep 27 '14 at 7:56 on
source share

Use the code below in TextView

  android:maxLength="65" 

Enjoy ...

+3
Sep 27 '14 at 7:42 on
source share
+1
Feb 05 2018-12-12T00:
source share

As mentioned in https://stackoverflow.com/a/165129/ and using https://stackoverflow.com/questions/88588/... using

 android:minEms="2" 

should be enough to achieve the goal.

0
Mar 28 '17 at 8:09
source share

you can extend the TextView class and overwrite the setText () function. In this function, you check the length of the text or phrase.

-5
Feb 05 2018-12-12T00:
source share



All Articles