Ganesh S S
Ganesh S S

Reputation: 571

How to truncate a TextView leaving certain number of characters at the end of the text view in Android Studio?

I have a TextView where I set a text ( for eg: Aaron Taylor Johnson [Participant] ). The TextView should truncate, where [Participants] should be present even after truncation.Something like this:

Aaron Taylor Jo...[Participant]

Aaron Tay...[Participant]

Can somebody help me out?

Upvotes: 2

Views: 1780

Answers (3)

Rohit Kumar
Rohit Kumar

Reputation: 69

Check

if (textview.getText().toString().contains([Participant]))
{
String str = textview.getText().toString() ; 
textview.setText(str.subString(1,k)+"...[Participant]") ; 
} 

Where k is the length of the starting string you want in your textView.

Upvotes: -1

Hamza Khan
Hamza Khan

Reputation: 1521

First you can use TextView attribute android:ellipsize="middle" but it won't solve your problem as it would truncate it in the middle of text, it doesn't matter if it's cutting [Participant] name too.

What you need is two TextView in a single LinearLayout, 1st TextView is for general text and 2nd is for participant name.

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/tv1"
        android:layout_width="0dp"
        android:layout_weight="1"
        android:layout_height="wrap_content"
        android:maxLines="1"
        android:text="Hello Lorem Ipsum Lorem Ips sdafjdskafj kdlsajf kljds gfsad fsda "
        android:ellipsize="end" />

    <TextView
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" Participant"/>

</LinearLayout>

Upvotes: 2

DalveerSinghDaiya
DalveerSinghDaiya

Reputation: 495

You can do it using xml attribute of the textView as following.

<TextView
        android:id="@+id/tv"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:text="An example"
        android:singleLine="true"
        android:ellipsize="middle"
        />

Upvotes: 2

Related Questions