2011-01-12 57 views
8
{ 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返回错误的值更小的...那比真实高度小。的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:

回答

14

问题是相当老,但我有类似的问题,所以我会描述什么是错的。 其实,在listItem.measure()参数用于错了,你应该设置这样的事情:

listItem.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)) 

然而,小心未指定宽度测量规范,它会忽略所有的布局PARAMS,甚至屏幕尺寸,所以得到正确的高度,首先得到最大宽度查看可以使用和呼叫措施()是这样的:

listItem.measure(MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); 
+0

这真的帮了我。非常感谢! – myforums 2014-02-13 23:13:39

0

这也给当ListView项的XML文件具有填充错误值。删除填充,尝试使用边距,它将完美工作。