计算listview的条目高度来动态设定listv的高度

来源:互联网 发布:nginx配置两个域名 编辑:程序博客网 时间:2024/06/05 16:23

有时会遇到一种情况就是给定你一个固定高度了,让你的条目在里边显示,在条目很多的情况下是没有问题的,但在条目只有一两条时就会存在空白,影响美观,所以动态设定listview也有必要;
首先是计算listview的条目总高度,这个网上一搜一大把:
其实原理就是将每一个条目取出来计算高度相加,最后再加上条目之间的间距高度(这个间距是不能忽略的)

public class Utility {    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);    }    public static int getListViewHeightBasedOnChildren(ListView listView){        ListAdapter listAdapter = listView.getAdapter();        if (listAdapter == null) {            // pre-condition            return 0;        }        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();        }        int heights= totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));        return heights;    }}
  /**         * 填充数据         */        CarWarnDetailAdapter adapter = new CarWarnDetailAdapter(getActivity());        adapter.setData(cList);        lv.setAdapter(adapter);        /**         *计算listview的条目高度动态设定其高度         */        int heights = Utility.getListViewHeightBasedOnChildren(lv);        ViewGroup.LayoutParams params = lv.getLayoutParams();        if(heights<335){            params.height = heights;            lv.setLayoutParams(params);        }else{            params.height=335;            lv.setLayoutParams(params);        }

在你将数据添加到适配器和listview设置适配器后再进行这些步骤,不然是条目是没有数据的,高度自然也就没有;

0 0