Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get listview height in android?

I need to find the height of android ListView with custom ListVAdapter. Each of ListView items can be of varying height. I have tried the following code which I found here:

public static void setListViewHeightBasedOnChildren(ListView listView) {

        ListAdapter listAdapter = listView.getAdapter(); 
        if (listAdapter == null) {
            return;
        }

        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, MeasureSpec.UNSPECIFIED);
            totalHeight += listItem.getMeasuredHeight();
        }

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

But it doesn't give actual height; it gives same height for all list items. Is it possible to find ListView height with list items of varying height?

like image 287
althaf_tvm Avatar asked Dec 11 '12 05:12

althaf_tvm


2 Answers

Based on @jeevamuthu code.

public static int getLVHeight(ListView listView) {
    ListAdapter adapter = listView.getAdapter();
    int height = 0;
    int count = adapter.getCount();
    for (int i = 0; i < count; i++) {
        View view = adapter.getView(i, null, listView);
        view.measure(
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        height += view.getMeasuredHeight();
    }
    height += listView.getDividerHeight() * (count - 1);
    return height;
}
like image 89
CoolMind Avatar answered Sep 21 '22 00:09

CoolMind


private int getTotalHeightofListView() {

    ListAdapter LvAdapter = lv.getAdapter();
    int listviewElementsheight = 0;
    for (int i = 0; i < mAdapter.getCount(); i++) {
        View mView = mAdapter.getView(i, null, lv);
        mView.measure(
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
                MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        listviewElementsheight += mView.getMeasuredHeight();
    }
    return listviewElementsheight;
}

try this code.

like image 39
jeevamuthu Avatar answered Sep 23 '22 00:09

jeevamuthu