Denis Kanygin
Denis Kanygin

Reputation: 1133

How to get accurate ListView height at runtime?

I need to get accurate listView height at runtime.

When I use code below, height of each listItem is incorrect.

            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();
            }
            params.height = totalHeight + listview.getDividerHeight()* (listAdapter.getCount() -1);
            listview.setLayoutParams(params);
            listview.requestLayout();

when I use getChild version, Height is accurate but total count is off...

        int total = 0;
        for (int i = 0; i < listview.getChildCount(); i++) {
            View childAt = listview.getChildAt(i);
            if (childAt == null)
                continue;

            int childH = childAt.getMeasuredHeight();
            total += childH;
        }
        int div = listview.getDividerHeight();
        total += (div * (listAdapter.getCount() - 1));

        if (params.height != total) {
            getLogger().info("setting measured buttons list to height: " + total);
            params.height = total;
            listview.requestLayout();
            ViewParent parent = listview.getParent();

Have you run into this issue?

Upvotes: 1

Views: 5892

Answers (2)

Apoorv
Apoorv

Reputation: 13520

If you just want to find the height of listView you can use

listView.post(new Runnable()
{
    public void run()
    {
        listView.getHeight();
    }
});

Upvotes: 9

H N Sharma
H N Sharma

Reputation: 41

listItem.measure(0, 0); parameters of measure 0,0 use first parameter MeasureSpec.makeMeasureSpec(listWidth, MeasureSpec.EXACTLY) and second parameter MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) follow this code

public static void getTotalHeightofListView(ListView listView) {

    ListAdapter mAdapter = listView.getAdapter();

    int totalHeight = 0;
    int listWidth = listView.getMeasuredWidth();

    for (int i = 0; i < mAdapter.getCount(); i++) {
        View mView = mAdapter.getView(i, null, listView);

        mView.measure(
                MeasureSpec.makeMeasureSpec(listWidth, MeasureSpec.EXACTLY),

                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));

        totalHeight += mView.getMeasuredHeight();
        Log.w("HEIGHT" + i, String.valueOf(totalHeight));

    }

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

}

Upvotes: 2

Related Questions