ListView嵌套在ScrollView内显示不全的解决办法

ListView嵌套在ScrollView里面,只能够显示第一条数据。

因为ListView其实也是一个scrollView,scrollView默认是禁止嵌套的,起码导致内部的scrollView无法正确计算高度。[为什么会无法正常计算?]

解决办法也很简单,就是手动计算listView的高度并动态设置。

public static void setListViewHeightBaseOnChildren(ListView listView) {
        if (listView != null) {
            ListAdapter adapter = listView.getAdapter();
            int totalHeight = 0;
            int count = adapter.getCount();
            for (int i = 0; i < count; i++) {
           //View child = listView.getChildAt(i);//crash[why?]
                View child = adapter.getView(i, null, listView);
                child.measure(0, 0);
                totalHeight += child.getMeasuredHeight();//有关获取一个view高度的方法?
            }
            if (count > 0) {
                totalHeight += (count - 1) * listView.getDividerHeight();
            }
            LayoutParams params = listView.getLayoutParams();
            params.height = totalHeight;
            listView.setLayoutParams(params);
        }
    }

 

 

posted @ 2013-07-02 20:15  西瓜君  阅读(322)  评论(0)    收藏  举报