1

I am using the method below to set the height of the ListView to the height of the items. The problem is that I have a few items where the text is too long so it continues on the next line. For those items I don't get the proper height but the height of a single line item. How can I get it to work for multiple lines items too?

public boolean setListViewHeightBasedOnItems(ListView listView) {

    ListAdapter listAdapter = listView.getAdapter();
    if (listAdapter != null) {
        int numberOfItems = listAdapter.getCount();
        // Get total height of all items.
        int totalItemsHeight = 0;
        for (int itemPos = 0; itemPos < numberOfItems; itemPos++) {
            View item = listAdapter.getView(itemPos, null, listView);
            float px = 300 * (listView.getResources().getDisplayMetrics().density);
            item.measure(View.MeasureSpec.makeMeasureSpec((int)px, View.MeasureSpec.AT_MOST), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

            totalItemsHeight += item.getMeasuredHeight();
        }

        // Get total height of all item dividers.
        int totalDividersHeight = listView.getDividerHeight() *
                    (numberOfItems - 1);

        // Set list height.
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalItemsHeight + totalDividersHeight;
        listView.setLayoutParams(params);
        listView.requestLayout();

        return true;
    } else {
        return false;
    }

}

My item layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:paddingTop="3dp"
    android:paddingBottom="3dp"
    android:layout_height="wrap_content">

    <TextView
        android:textColor="@color/black"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/itemName"
        android:layout_marginRight="5dp"
        android:layout_gravity="right"
        android:layout_centerVertical="true"
        android:layout_toStartOf="@+id/itemData"
        android:layout_alignParentStart="true" />

    <TextView
        android:textColor="@color/black"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Text"
        android:id="@+id/itemData"
        android:layout_marginRight="10dp"
        android:layout_alignBaseline="@+id/itemName"
        android:layout_alignParentEnd="true" />

</RelativeLayout>
SilentKiller
  • 6,944
  • 6
  • 40
  • 75
Bart Bergmans
  • 4,061
  • 3
  • 28
  • 56

0 Answers0