set ListView Parent Height Based On Children - Android User Interface

Android examples for User Interface:ListView

Description

set ListView Parent Height Based On Children

Demo Code


//package com.java2s;
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 setListViewParentHeightBasedOnChildren(
            ListView listView, int attHeight) {
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = (int) (getListViewHeightBasedOnChildren(listView)
                + attHeight + 0.5);/* ww w . ja v a2  s.  co  m*/
        listView.setLayoutParams(params);

        System.out.println("params.height:" + params.height);

        LinearLayout linearLayout = (LinearLayout) listView.getParent();

        // android.widget.LinearLayout.LayoutParams params2 = new
        // android.widget.LinearLayout.LayoutParams(
        // LayoutParams.MATCH_PARENT, params.height);
        //
        // params2.setMargins(10, 0, 10, 10);

        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();
            System.out.println("itemHeight itemHeight:" + itemHeight);
            totalHeight += itemHeight;

        }

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

        return height;
    }
}

Related Tutorials