简体   繁体   中英

How to calculate total row heights of listView in android?

I used this code to get the total heights of listview row items but it did not returns the actual height. Here is the used code

public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter(); 
        if (listAdapter == null) {
            // pre-condition
            return;
        }

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

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

For example: I have a listview with 20 rows and each rows height is different from each others suppose that 200,300,500. When I use this above code, it did not returns actual height for me. Also I tried this answer : Android: How to measure total height of ListView But did not works. How can I get rid of this problem. Can anyone explain this solution??

View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();

The core of the function is these three lines, it try to measure each view. The 0 in listItem.measure(0, 0) is equals to MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)

Mostly it will calculate the accurate height of the listview. There is one exception, when the view content is too much and will wrap line, ie there are to many lines of text. In such situation, you should specified a accurate widthSpec to measure(). So change listItem.measure(0, 0) to

// try to give a estimated width of listview
int listViewWidth = screenWidth - leftPadding - rightPadding; 
int widthSpec = MeasureSpec.makeMeasureSpec(listViewWidth, MeasureSpec.AT_MOST);
listItem.measure(listViewWidth, 0)

UPDATE about the formula here

int listViewWidth = screenWidth - leftPadding - rightPadding; 

It's just an example to show how you can estimate the width of the width of listview, the formula is based on the fact that width of listview ≈ width of screen . The padding is set by your self, maybe 0 here. This page tells how to get screen width. In general, it's just a sample, and you can write your own formula here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM