set ListView Height Based On Content - Android User Interface

Android examples for User Interface:ListView

Description

set ListView Height Based On Content

Demo Code


//package com.java2s;

import android.util.Log;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;

public class Main {
    public static void setListViewHeightBasedOnContent(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null)
            return;

        int totalHeight = listView.getPaddingTop()
                + listView.getPaddingBottom();
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            if (listItem instanceof ViewGroup) {
                listItem.setLayoutParams(new ViewGroup.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT));
            }//from  w  ww. j  a va2  s.co m
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);

        Log.d("ViewUtils", "setListViewHeightBasedOnContent: "
                + listAdapter.getCount() + " items, height: " + totalHeight);
    }
}

Related Tutorials