【android积累】ScrollView和ListView问题

ScrollView和ListView一起使用会有冲突,ListView显示不全。 如何解决网上也有很多例子,这里只说两种简单的方案。

1. 手动计算ListView高度,方法如下:

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);  
    }  

这里使用measuredHeight获取高度,measuredHeight并不是实际高度,因此该方法计算出的高度与实际的高度会有误差。

 

2. 重写ListView的onMeasure方法,重新计算每个子Item的高度

public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        //根据模式计算每个child的高度和宽度
        int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST);
        super.onMeasure(widthMeasureSpec, expandSpec);
    }

 

posted @ 2012-10-09 11:50  yyyyy5101  Views(3060)  Comments(1Edit  收藏  举报