{ 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 包含具有除换行符以外的长文本的 TextViews)。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:
最佳答案
这个问题比较老了,但我遇到了类似的问题,所以我会描述哪里出了问题。 其实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));
关于android - ViewGroup{TextView,...}.getMeasuredHeight 给出的错误值小于实际高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4668939/