Skip to content Skip to sidebar Skip to footer

Android ListView Height To Wrap To The Height Of One Single List Item

I'm trying to make a view that contains 'two' ListViews. The first one's height should be equal to a single list item height, and the second ListView's height should take up the re

Solution 1:

The real question is, what benefit do you hope to achieve by having a ListView that only shows 1 item - why not just display that item in a standard View?


If you have a fixed height ListItem, you can set this as the android:layout_height attribute:

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

  <ListView
    android:id="@+id/top_list_view"
    android:layout_width="match_parent"
    android:layout_height="?android:listPreferredItemHeight"
    android:background="@android:color/holo_green_dark" />

  <ListView
    android:id="@+id/bottom_list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/holo_blue_bright" />
</LinearLayout>

two listviews, with the top listview having a fixed height


Solution 2:

While I agree that the code snippet in the OP contributes nothing to the question, the question itself is very reasonable and I had to do exactly the same thing in my project.

The way this can be done (assuming all items in the list have the same height) is by measuring an item once and assigning its height to the listview. Here is what worked for me (adapter's code):

    private int cellHeight = -1;
    ...

    public override View getView(int position, View convertView, ViewGroup parent)
    {
        View view = context.LayoutInflater.Inflate(R.layout.list_item, null);
        ...

        if (cellHeight == -1)
        {
            // Measure the cell once and set this height on the list view. Won't work correctly if 
            // cells have different heights
            int UNBOUNDED = MeasureSpec.MakeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
            view.Measure(UNBOUNDED, UNBOUNDED);
            cellHeight = view.getMeasuredHeight();
            LayoutParameters para = listview.getLayoutParams();
            para.Height = cellHeight;
            listview.setLayoutParams(para);
        }

        return view;
    }

Post a Comment for "Android ListView Height To Wrap To The Height Of One Single List Item"