{ January 14, 2011... I have given up to u开发者_StackOverflow社区se 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(the ViewGroup is containing TextViews having long text except line-feed-character).getMeasuredHeight returns wrong value... that is smaller than real height.
how to get rid of this problem?
here is the java code:
/*
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);
}
and here is the list_item_comments.xml:
The question is rather old, but I had similar problem, so I'll describe what was wrong. Actually, parameters in listItem.measure() are used wrong, you should set something like this:
listItem.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED))
However, be careful with unspecified width measure spec, it will ignore all layout params and even screen dimensions, so to get correct height, first get maximum width View can use and call measure() this way:
listItem.measure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
This is the only solution i have found so far. http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html
It also gives wrong value when Your xml file of listview item has padding. Remove padding, try using margin and it will work perfectly.
精彩评论