Android 關於在ScrollView中加上一個ListView,ListView內容顯示不完全(總是顯示第一項)的問題的兩種簡單的解決方案

有這樣一個需求:

  1.顯示一個界面,界面上有一個列表(ListView),列表上面有一個可以滾動的海報。

  2.要求在ListView滾動的過程中,ListView上面的海報也可以跟着ListView滾動。

我們的一般解決方案:

1.使用ScrollView嵌套這一個ListView。

對,這樣的佈局本身是沒喲什麼問題的。但是問題來了,當你運行你的界面的時候,突然發現,你的列表中明明有好多項,但是爲什麼只顯示一項呢?仔細檢查你會發現,不是列表只顯示一項,而是其它的項被佈局本身遮住了。

 

 

怎麼辦呢?下面將給出兩種相對簡單的解決方案:

第一種:禁用ListView的滾動(Scroll)。

第二種:計算ListView中每一項的高度,然後根據每一項的高度“乘以”項數,計算出ListView的總高度。

 

下面給出第一種方法的代碼展示:

import android.widget.ListView;

public class MyListView extends ListView{
    public MyListView(android.content.Context context,android.util.AttributeSet attrs){  
        super(context, attrs);  
    }  
    /** 
     * 設置不滾動 
     */  
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
    {  
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,  
                MeasureSpec.AT_MOST);  
        super.onMeasure(widthMeasureSpec, expandSpec);  
  
    }  
}

以下是第二種方法的的代碼:

/**動態改變listView的高度*/
    public void setListViewHeightBasedOnChildren(ListView listView) {
          ListAdapter listAdapter = listView.getAdapter();
          if (listAdapter == null) {
           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();
//           totalHeight += 80;
          }
          ViewGroup.LayoutParams params = listView.getLayoutParams();
//          params.height = 80 * (listAdapter.getCount() - 1);
//          params.height = 80 * (listAdapter.getCount());
          params.height = totalHeight
            + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
          ((MarginLayoutParams) params).setMargins(0, 0, 0, 0);
          listView.setLayoutParams(params);
          
         }

轉載地址:http://www.cnblogs.com/tony-yang-flutter/p/3344636.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章