Skip to content Skip to sidebar Skip to footer

Determine ListView Height Before Loading The List

Is it possible to determine the height of a ListView before it is rendered on the screen? If my ListView were to have, say 3 items, and the height is confined to these 3 items (and

Solution 1:

Use the following method to get and set the height based upon children present

 private static void setListViewHeightBasedOnChildren(ListView iListView) {
        ListAdapter listAdapter = iListView.getAdapter();
        if (listAdapter == null)
            return;

        int desiredWidth = View.MeasureSpec.makeMeasureSpec(iListView.getWidth(), View.MeasureSpec.UNSPECIFIED);
        int totalHeight = 0;
        View view = null;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            view = listAdapter.getView(i, view, iListView);
            if (i == 0)
                view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, RelativeLayout.LayoutParams.WRAP_CONTENT));

            view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = iListView.getLayoutParams();
        params.height = totalHeight + (iListView.getDividerHeight() * (listAdapter.getCount() - 1));
        Log.d("TAG", "ListView Height --- "+params.height);
        iListView.setLayoutParams(params);
        iListView.requestLayout();
    }

Solution 2:

You will have to calculate the height yourself if you have kept the height of each item fixed. A view can't return its height before it is made


Post a Comment for "Determine ListView Height Before Loading The List"