Android: TextView automatically truncate and replace last 3 char of String

JavaAndroidTextview

Java Problem Overview


If a String is longer than the TextView's width it automatically wraps onto the next line. I can avoid this by using android:singleLine (deprecated) or by setting android:inputType="text". What I need now is something that replaces the last 3 characters of my String with "...". Since I'm not using a monospace font this will always be different depending on the letters used in my String. So I'm wondering what's the best way to get the last 3 characters of a String in a TextView and replace them. Maybe there's already something implemented in the Android framework, since this must be a common problem.

Java Solutions


Solution 1 - Java

You should be able to use the "ellipsize" property of a text view:

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

You may also need to apply gravity values to the layout too; I have sometimes seen "auto-stretching" views without them.

Solution 2 - Java

Found an interesting work-a-round for this problem.

maxLines=1
ellipsize=end
scrollHorizontally=true

The trick is that last statement about horizontal scrolling .... check it out. It at least works on v2.2.

Solution 3 - Java

Programmatically, you can use:

TextView tx = new TextView(this);
tx.setTextSize(13);
tx.setGravity(Gravity.CENTER);
tx.setTop(90);
tx.setText("Long text here");
tx.setTextColor(Color.BLACK);
tx.setSingleLine(true);
tx.setEllipsize(TruncateAt.END);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionznqView Question on Stackoverflow
Solution 1 - JavaNateView Answer on Stackoverflow
Solution 2 - JavaBonanzaDriverView Answer on Stackoverflow
Solution 3 - JavaxevserView Answer on Stackoverflow