2

My first question on SO so let me know if I phrase something wrong. Just like the title says, I wish the text within each item of my listview to stay on one row (if the are longer than what fits make them end with a "..." or something like it). I have a kind of a "recent searches" in my android app which leaves them all in an array of strings, I then display them in the listview like the following:

    ListView recenlist = (ListView) findViewById(R.id.recentChatList);

       ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, recCharArray);
       recenlist.setAdapter(adapter);
       recenlist.setTextFilterEnabled(true);

where recCharArray contains a bunch of strings that varry in size and are displayed in the listview. However, they should stay on one row but don't. Ive tried singleLine, maxLines but I can't get it to work. Any ideas?

and then in the XML:

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/recentChatList"
    android:layout_below="@+id/searchField"
    android:layout_alignParentStart="true"
    android:layout_marginTop="45dp" />

I've been searching around a lot but I can't seem to find a solution that works for me, do I need a new approach to this? Do I need to change something completely?

Thanks in advance!

leQu
  • 55
  • 5

2 Answers2

2

Note that you are using a predefined xml file android.R.layout.simple_list_item_1 for the rows in your ListView. You can see the code inside this file here: https://github.com/android/platform_frameworks_base/blob/master/core/res/res/layout/simple_list_item_1.xml

Try to make your own layout file (custom_simple_list_item.xml) in the layouts folder with a single TextView and set android:singleLine = "true" and android:ellipsize = "end". Reusing the code in the previous link, something like that:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingStart="?android:attr/listPreferredItemPaddingStart"
    android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:singleLine = "true"
    android:ellipsize = "end"
  />

Then, use this file in the adapter initialization:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.custom_simple_list_item, recCharArray);
Jofre Mateu
  • 2,390
  • 15
  • 26
0

You can use a custom Adapter, your Adapter will contain a TextView and the TextView should be on a single line (singleLine="true"). A link to make a custom adapter for ListView.

Community
  • 1
  • 1
issathink
  • 1,220
  • 1
  • 15
  • 25