如何在android中获取listview高度?

前端之家收集整理的这篇文章主要介绍了如何在android中获取listview高度?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我需要找到具有自定义ListVAdapter的 Android ListView的高度.每个ListView项目都可以有不同的高度.我试过下面的代码,我在这里找到:
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();
    }

但它并没有给出实际的高度;它为所有列表项赋予相同的高度.可以找到具有不同高度的列表项的ListView高度?

解决方法

private int getTotalHeightofListView() {

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

尝试这个代码.

原文链接:https://www.f2er.com/android/310343.html

猜你在找的Android相关文章