How to cut off too long lines of text in Lists with ellipsize

If you are using lists in your app, and some of the list items have too long text, making it wrap to several lines like item number three in the following image, then this trick will show you how to create better looking lists.

Before, Text wrapping to two lines:
before

Your custom list item xml layout file may look like this:

<?xml version="1.0" encoding="utf-8"?>  
 <TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/list_item_name"
 android:layout_gravity="center"
 android:paddingLeft="8dp"
 /*...*/
 />

If you change it by adding the ellipsize and singleLine attributes, the long text will wrap when it goes out of its boundaries:

<?xml version="1.0" encoding="utf-8"?>  
 <TextView xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:id="@+id/list_item_name"
 android:layout_gravity="center"
 android:paddingLeft="8dp"
 /*...*/
 android:ellipsize="end"
 android:maxLines="1"
 android:singleLine="true"

/>

Text is now nicely cut off with an ellipsize …

after

This will not only look better, but also keep all list items at the same height.

It’s the singleLine attribute that does the trick, but by using the ellipsize attribute, you can also specify where you want the three periods to appear.

You can for example specify “middle” to have them appear in the middle of the text, thus showing the start and and of the text.

comments powered by Disqus