0

Following is my textview in android layout and I want that after a certain width of text, it adds '...' at the end of string. I don't want to do it in java while setting the text but want this to be handled by this textview itself. Is it possible?

<TextView
    android:id="@+id/list_contact_name"
    android:layout_width="220dp"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@+id/list_contact_icon"
    android:paddingLeft="10dp"
    android:paddingBottom="10dp"
    android:textColor="#222"
    android:text="Sandeep Choudhary Mahabali"
    android:textSize="18sp" />

3 Answers3

4

add these attributes to your textview :

android:maxLines="1"
android:ellipsize="end" 
Waqar Ahmed
  • 5,005
  • 2
  • 23
  • 45
1

Add these attributes to your TextView to restrict your TextView's text in one line and to add 3 dots ... at the end of line.

android:singleLine="true"
android:ellipsize="end" 
Hamid Shatu
  • 9,664
  • 4
  • 30
  • 41
  • android:singleLine="true" is deprecated.. – Waqar Ahmed Apr 29 '14 at 03:59
  • @AshuKumar...please provide the reference link for `android:line="1"` as you suggested. I only found [`android:lines`](https://developer.android.com/reference/android/widget/TextView.html#attr_android:lines) attribute but no `android:line`. – Hamid Shatu May 17 '17 at 05:59
0

Extend the TextView class, override setText and trim and add your "..." there. If desired, add an attribute that defines how long the text should be before being trimmed, then you can set each TrimmedTextView length in xml as well.

public class TrimmedTextView extends TextView {

    @Override
    public void setText(CharSequence text, BufferType type) {
        int maxLength = 10;
        String value = text.toString();
        if (text.length() > maxLength) {
            value = text.subSequence(0, maxLength) + "...";
        }
        super.setText(value, type);
    }
}
r2DoesInc
  • 3,759
  • 3
  • 29
  • 60