Johann
Johann

Reputation: 29867

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 the ListView doesn't take up the entire screen's height), can I determine the height before Android displays the items on the screen?

Upvotes: 3

Views: 119

Answers (2)

pvn
pvn

Reputation: 2106

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

Upvotes: 0

Napolean
Napolean

Reputation: 5543

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();
    }

Upvotes: 2

Related Questions