如何获得android中的listview高度?

我需要find自定义ListVAdapter的Android ListView的高度。 每个ListView项目可以有不同的高度。 我已经尝试了我在这里find的以下代码:

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

但它并没有给出实际的高度; 它给所有列表项目相同的高度。 有没有可能findListView高度与不同高度的列表项目?

Solutions Collecting From Web of "如何获得android中的listview高度?"

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

试试这个代码。

当您调用measure(0, MeasureSpec.UNSPECIFIED) ,您告诉视图布局系统使用无限宽度,所以例如TextViews可能只是stream向一行。 尝试传递你的列表视图的宽度:

 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之后调用此onMeasure ,否则listView.getMeasuredWidth()将返回0。

你可以使用getHeight():

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

或者按照这个答案 。

基于@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; }