Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically truncate TextView text so as not to overlap another TextView

I have a ListView that displays a bunch of homework assignments. The ListView items use a FrameLayout to position two TextViews. The first TextView is aligned to the left, and the second is aligned to the right. (Both are aligned in the center vertically.) The first displays a snippet of the assignment description, and the second displays the due date.

What I want to do is make it so that the due date takes up as much space as it needs and the description fills up the remaining space, like so:

|----------------------------------------------------|
| Read pgs 15-35, update tim... Fri, May 4|
|----------------------------------------------------|

Right now the description text will continue on to overlap the date. It will truncate at the end of the line though.

Is there anyway I can do this in XML, or do I have to do it in code by shortening the string before I set the TextView value (presumably in my getView call)? If I did it in code, I'd have to calculate the amount of horizontal space the strings would take up figure out how short the description needs to be. That seems like it could get messy...

Any other suggestions on how to accomplish this are greatly appreciated!

like image 995
mightimaus Avatar asked May 03 '12 20:05

mightimaus


2 Answers

Try using the ellipsize attribute like :

<TextView android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:ellipsize="end"
      android:singleLine="true"/>

Note that Android, or at least some versions, require both the "ellipsize" and the "singleline" attributes in order for the system to actually do the truncation and add the ellipsis.

like image 75
ChristopheCVB Avatar answered Oct 26 '22 19:10

ChristopheCVB


Instead of a FrameLayout, this is the perfect place for a LinearLayout or RelativeLayout in combination with ellipsize:

<LinearLayout
  android:orientation="horizontal"
  android:layout_width="match_parent"
  android:layout_height="wrap_content" >

  <TextView
    ...
    android:width="0dp"
    android:height="wrap_content"
    android:layout_weight="1" 
    android:ellipsize="end" />

  <TextView
    ...
    android:width="wrap_content"
    android:height="wrap_content"
    android:layout_weight="0" />

</LinearLayout>

Or alternately

<RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="wrap_content" >

  <TextView
    ...
    android:id="@+id/secondTV"
    android:width="wrap_content"
    android:height="wrap_content"
    android:layout_weight="0" />

  <TextView
    ...
    android:width="0dp"
    android:height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_toLeftOf="@id/secondTV" 
    android:ellipsize="end"/>

</RelativeLayout>
like image 43
JRaymond Avatar answered Oct 26 '22 18:10

JRaymond