参见英文答案 >
Calculate the size of a list view or how to tell it to fully expand 12个
我需要测量ListView的总高度,但是看起来我一直在错误的值.我正在使用这段代码:
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(),
MeasureSpec.AT_MOST);
Log.w("DESIRED WIDTH", String.valueOf(listAdapter.getCount()));
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
Log.w("HEIGHT"+i, String.valueOf(totalHeight));
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight
+ (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
问题是我收到比我应得的更大的高度.每个列表项目的测量方式不同,所有项目都具有相同的高度,所以绝对不应该这样做.每个元素的高度至少是真实高度的两倍.
先谢谢你.
EDIT1:
我有两个ListViews,它们都有6-7个EditText字段的项目.如果用户想在EditText中写/删除值,我将显示/隐藏ListView.一切都很好,除非我想显示列表,它需要很多空间,因为方法计算的ListView需要很大的空间.因为这个ListView下面有很多空格.像需要三倍多的空白空间.