ScrollView與ListView合用(正確計算Listview的高度)的問題解決


最近做項目中用到ScrollView和ListView一起使用的問題,顯示的時候ListView不能完全正確的顯示,查了好多資料終於成功解決:
 

首先,ListView不能直接用,要自定義一個,然后重寫onMeasure()方法:

 

復制代碼代碼如下:

@Override  
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
    int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,  
            MeasureSpec.AT_MOST);  
    super.onMeasure(widthMeasureSpec, expandSpec);  

 

 

 

第二步:寫個計算listView每個Item的方法:

復制代碼代碼如下:

public void setListViewHeightBasedOnChildren(ListView listView) {

 

  // 獲取ListView對應的Adapter

  ListAdapter listAdapter = listView.getAdapter();

  if (listAdapter == null) {

   return;

  }

  int totalHeight = 0;

  for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回數據項的數目

   View listItem = listAdapter.getView(i, null, listView);

   listItem.measure(0, 0); // 計算子項View 的寬高

   totalHeight += listItem.getMeasuredHeight(); // 統計所有子項的總高度

  }

  ViewGroup.LayoutParams params = listView.getLayoutParams();

  params.height = totalHeight
    + (listView.getDividerHeight() * (listAdapter.getCount() - 1));

  // listView.getDividerHeight()獲取子項間分隔符占用的高度

  // params.height最后得到整個ListView完整顯示需要的高度

  listView.setLayoutParams(params);

 }

 

第三步:listview添加適配器后設置高度即可:

 

復制代碼代碼如下:

listView.setAdapter(adapter);  
new ListViewUtil().setListViewHeightBasedOnChildren(listView);  
 
 
 
 
 
 
 

項目中需要在ScrollView中套個ListView,ListView的Item是動態添加的,故高度也需要動態設置,在網上找了一天,發現文章出處都是在http://stackoverflow.com/questions/3495890/how-can-i-put-a-listview-into-a-scrollview-without-it-collapsing ,網上中文轉載,基本都是引用如下代碼:

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

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

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

測試下來發現,對Item內容是英文的情況還可以,有多行中文就不行了。其實,問題出在    listItem.measure(0, 0);   上, 在參考貼上有人已經給出了解決方法,就是先調用
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
然后改成調用    listItem.measure(desiredWidth, 0);   就可以了。

這點問題折騰了一天,細節決定成敗,古人誠不欺吾也。

 
 
 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM