2011-01-12 56 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文件具有填充錯誤值。刪除填充,嘗試使用邊距,它將完美工作。