ScrollView中嵌套ListView/ExpandableListView显示问题

来源:互联网 发布:软件项目经理责任制 编辑:程序博客网 时间:2024/05/21 05:07

android 官方不支持scrollview内部嵌套一个scrollview,所以listview嵌套listview或者scrollview嵌套ExpandableListView的话,listview的item是显示不全的,公司最近的项目中涉及到了这个问题,解决方法如下:

在设置了adapter之后,调用计算高度的方法即可;

ScrollView中嵌套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();      }            ViewGroup.LayoutParams params = listView.getLayoutParams();      params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));            listView.setLayoutParams(params);      }
ScrollView中嵌套ExpandableListView:

public static void setListViewHeightBasedOnChildren(ExpandableListView listView ) {             // 获取ListView对应的Adapter            ExpandableListAdapter listAdapter = listView.getExpandableListAdapter();             if (listAdapter == null) {                   // pre -condition                   return;            }             int totalHeight = 0;             for (int i = 0; i < listAdapter.getGroupCount(); i++) { // listAdapter.getCount()返回数据项的数目                  View listgroupItem = listAdapter .getGroupView(i, true, null, listView );                   listgroupItem.measure(0, 0); // 计算子项View 的宽高                   totalHeight += listgroupItem .getMeasuredHeight(); // 统计所有子项的总高度                  System. out.println("height : group" +i +"次" +totalHeight );                   for (int j = 0; j < listAdapter.getChildrenCount( i); j++) {                        View listchildItem = listAdapter .getChildView(i, j, false , null, listView);                         listchildItem.measure(0, 0); // 计算子项View 的宽高                         totalHeight += listchildItem.getMeasuredHeight(); // 统计所有子项的总高度                        System. out.println("height :" +"group:" +i +" child:"+j+"次"+ totalHeight);                  }            }            ViewGroup.LayoutParams params = listView .getLayoutParams();             params.height = totalHeight + ( listView.getDividerHeight() * (listAdapter.getGroupCount() - 1));             // listView.getDividerHeight()获取子项间分隔符占用的高度             // params.height最后得到整个ListView完整显示需要的高度             listView.setLayoutParams(params );      }

前者是实现项目中,订单中心一个订单对应多个商品list展示,后者是购物车一个人对应多个商品并添加支付等信息时使用,后者根据前者修改的,网上关于ExpandableListView计算高度的好像挺少的,就自己改写了。

OVER。

0 0
原创粉丝点击