3

I have created a layout with two textviews to display some content with text selection enabled. While try to ellipsize text, it does't work. If I disable the text selection, ellipsize works as expected. How to ellipsize text with text selection enabled?

And also, while adding paddingRight attribute to first textview (textview1), second textview (textview2) gets truncated at firstline eventhough I configured ellipize as "end". How to resolve the first line truncate issue?

Screenshot for ellipsize and first line truncation

XML layout file:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textview1"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:includeFontPadding="false"
        android:paddingRight="15dp"
        android:singleLine="true"
        android:text="Single Line 123456789 123456789"
        android:textColor="#f00"
        android:textIsSelectable="true"
        android:textSize="16dp" />

    <TextView
        android:id="@+id/textview2"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="1dp"
        android:ellipsize="end"
        android:includeFontPadding="false"
        android:maxLines="2"
        android:text="MultiLine123456789123456789123456789123456789 123456789123456789123456789"
        android:textColor="#000"
        android:textIsSelectable="true"
        android:textSize="16dp" />

</LinearLayout>

Thank you for any help you can offer.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
sathish
  • 91
  • 6

1 Answers1

0

An old question, but hopefully this will help someone who comes here looking for answers (as I did).

It appears that android:textIsSelectable and android:ellipsize are simply incompatible; text that is selectable won't ellipsize, full stop. So, here's a workaround:

  1. In your layout XML, go ahead and put android:ellipsize="end", but don't include android:textIsSelectable="true".
  2. After your view inflates, run the following Kotlin code on your TextView:
    myTextView.doOnNextLayout {
        myTextView.text = myTextView.layout.text
        myTextView.setTextIsSelectable(true)
    }

The key here is layout.text: that's the ellipsized version of myTextView's content. So effectively, we're manually ellipsizing our text here - and then we can safely make it selectable.

Sterling
  • 6,365
  • 2
  • 32
  • 40