{ January 14, 2011... I have given up to use setListViewHeightBasedOnChildren(ListView listView},
instead, I don't put my listview in a scrollview, and then just put other contents
into a listview by using ListView.addHeaderView() and ListView.addFooterView().
http://dewr.egloos.com/5467045 }
ViewGroup(ViewGroup包含具有除换行符之外的长文本的TextView).getMeasuredHeight返回错误的值...小于实际高度。
如何摆脱这个问题?
这是java代码:
/*
I have to set my listview's height by myself. because
if a listview is in a scrollview then that will be
as short as the listview's just one item.
*/
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int count = listAdapter.getCount();
for (int i = 0; i < count; i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(View.MeasureSpec.AT_MOST, View.MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
这里是list_item_comments.xml:
答案 0 :(得分:15)
问题相当陈旧,但我有类似的问题,所以我会描述错误。 实际上,listItem.measure()中的参数使用错误,您应该设置如下:
listItem.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
但是,请注意未指定的宽度测量规范,它会忽略所有布局参数甚至屏幕尺寸,因此要获得正确的高度,首先要获得最大宽度View可以使用并调用measure()这样:
listItem.measure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
答案 1 :(得分:0)
这是迄今为止我找到的唯一解决方案。 http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html
答案 2 :(得分:0)
当listview项的xml文件具有填充时,它也会给出错误的值。删除填充,尝试使用边距,它将完美地工作。