Android ScrollView嵌套ListView或者GridView显示不全

ScrollView嵌套ListView或者GridView显示不全是因为滑动冲突,计算ListView或者GridView的高度就行了 
/**  * 根据数据设置ListView,GridView的高度,从而确定其在ScrollView的显示高度  *  *  */ public class ListViewUtility {

    public static 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();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();

        int height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount()));
        params.height = height;
        listView.setLayoutParams(params);
    }

    public void setGridViewHeight(GridView gridview, int num) {
        ListAdapter Adapter = gridview.getAdapter();
        if (Adapter == null) {
            return;
        }

        int size = Adapter.getCount();
        int row = size / num;
        if (size % num != 0) {
            row += 1;
        }
        gridview.measure(0, 0);
        View gridItem = Adapter.getView(0, null, gridview);
        gridItem.measure(0, 0);
        int height = gridItem.getMeasuredHeight();

        ViewGroup.LayoutParams params = gridview.getLayoutParams();
        params.height = row * height;
        gridview.setLayoutParams(params);
    }

    public int getGridViewHeight(GridView gridview, int num) {
        ListAdapter Adapter = gridview.getAdapter();
        if (Adapter == null) {
            return 0;
        }

        int size = Adapter.getCount();
        int row = size / num;
        if (size % num != 0) {
            row += 1;
        }
        gridview.measure(0, 0);
        View gridItem = Adapter.getView(0, null, gridview);
        gridItem.measure(0, 0);
        int height = gridItem.getMeasuredHeight();
        return row * height;
    }

}

你可能感兴趣的:(优化,android,ListView,GridView,控件)