10

我需要使用自定义 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 高度?

4

4 回答 4

15
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;
}

试试这个代码。

于 2013-01-10T17:23:24.840 回答
2

当您调用 时measure(0, MeasureSpec.UNSPECIFIED),您是在告诉视图布局系统使用无限宽度,因此例如TextViews可能只流到单行。尝试传递列表视图的宽度:

public static void setListViewHeightBasedOnChildren(ListView listView) {
    ListAdapter listAdapter = listView.getAdapter(); 
    int totalHeight = 0;
    int listWidth = listView.getMeasuredWidth();
    for (int i = 0; i < listAdapter.getCount(); i++) {
        View listItem = listAdapter.getView(i, null, listView);
        listItem.measure(
            MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
            MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        totalHeight += listItem.getMeasuredHeight();
    }
    // ...update list height
} 

您还需要确保onMeasure在列表视图上调用它之后调用它,否则listView.getMeasuredWidth()将返回 0。

于 2014-03-07T23:10:34.223 回答
1

您可以使用 getHeight():

System.out.println("height of list view..."+listview.getHeight());

或者按照这个答案

于 2013-01-10T20:07:32.867 回答
1

基于@jeevamuthu 代码。

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;
}
于 2017-07-25T07:43:03.500 回答