TextView maxLength ellisize not working

2.7k Views Asked by At

I have a TextView, that should be max 15 characters and at the end it should have three dots. With my XML it cuts 15 characters but doesn't add three dots ... at the end.

IMPORTANT: I know it works when I limit the text with line count - android:maxLines="2". But I need limit it with max characters count, as stated in question.

<TextView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:maxLength="15"
    android:ellipsize="end"
    tools:text="123456789qwertyuiopasdfghjklzxcvbnm"
    android:textSize="50sp"
/>

The result:

enter image description here

2

There are 2 best solutions below

3
On

Try this one solution:

 <TextView
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:ellipsize="end"
    android:singleLine="true"
    android:maxLines="1"
    android:text="123456789qwertyuiopasdfghjklzxcvbnm"
    android:textSize="50sp"
    />

Hope this help you...if you need any help you can ask

3
On

I'm not sure how or if you can do what you want in XML.

At least i don't know how - but i have an alternative solution for you.

public void ellipsizeText(TextView tv){
    int maxLength = 13;
    if(tv.getText().length() > maxLength){
        String currentText = tv.getText().toString();
        String ellipsizedText =  currentText.substring(0, maxLength - 3) + "...";
        tv.setText(ellipsizedText);
    }
}

So i just made it as a method that take a textview in as a parameter. It's really quite simple, you change the maxLength to the desired max length of the string. In this case it is set to 13 since it replaces the last 3 chars with "...", which then results in a String that is still 13 chars long, but with the first 10 being the actual text and the last 3 being "...".

In your main project you would change maxLength to 150 (or 153, if you want 150 visible chars from the string)

Hope you can use this, and if you got any questions let me know.