set ListView Height Based On Children - Android android.widget

Android examples for android.widget:ListView

Description

set ListView Height Based On Children

Demo Code

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

public class Main{

    public static void setListViewHeightBasedOnChildren(ListView listView,
            int attHeight) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }/*from   w  w  w.  j  ava2 s .c o  m*/

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1))
                + attHeight;
        listView.setLayoutParams(params);

    }
    public static void setListViewHeightBasedOnChildren(ListView listView) {

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = getListViewHeightBasedOnChildren(listView);
        listView.setLayoutParams(params);
        LinearLayout linearLayout = (LinearLayout) listView.getParent();
        linearLayout.setLayoutParams(params);
    }
    public static int getListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return 0;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            int itemHeight = listItem.getMeasuredHeight();
            totalHeight += itemHeight;

        }

        int height = (int) (totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1)) + 0.5);

        return height;
    }

}

Related Tutorials