2016-08-17 58 views
0

大家好,我需要幫助將動態高度設置爲列表視圖。如何將動態高度設置爲列表視圖

在我的任務有一個listView內滾動視圖,所以我需要設置動態高度列表視圖,使任務完成在滾動視圖中可行。

我使用以下代碼從how to change the height of the ListView dynamically in andrtoid。 此代碼運行良好,但問題是與此代碼,它使雙高度列表視圖。

想,如果有隻3項列表視圖則使ListView控件的高度等於6項

我想知道如何解決它。

這是我的代碼。

public class Utility { 
     public static void setListViewHeightBasedOnChildren(ListView listView) { 
      ListAdapter listAdapter = listView.getAdapter(); 
      if (listAdapter == null) { 
       // pre-condition 
       return; 
      } 

      int totalHeight = 0; 
      int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.AT_MOST); 
      for (int i = 0; i < listAdapter.getCount(); i++) { 
       View listItem = listAdapter.getView(i, null, listView); 
       listItem.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED); 
       totalHeight += listItem.getMeasuredHeight(); 
      } 

      ViewGroup.LayoutParams params = listView.getLayoutParams(); 
      params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); 
      listView.setLayoutParams(params); 
      listView.requestLayout(); 
     } 
    } 

和IM列表視圖中使用的活動像:

SimpleAdapter simpleadapter = new SimpleAdapter(getApplicationContext(), alist, R.layout.fragmentsrow, getItems, setItems); 

     ListViewWelcomePage.setAdapter(simpleadapter); 

     Utility.setListViewHeightBasedOnChildren(ListViewWelcomePage); 
+0

首先,如果你使用listview,然後刪除滾動查看。默認情況下,如果列表中有更多數據,它將滾動。 – Tara

+0

我需要滾動視圖宏我不能刪除滾動視圖只是因爲列表視圖下方有另一個項目,我需要使用滾動視圖來顯示 – sunny

+0

在列表視圖中使用頁腳或標題而不是在滾動視圖中嵌套列表視圖。像[這個](http://stackoverflow.com/questions/4265228/how-to-add-a-footer-in-listview) – MrOnyszko

回答