android 控件 scrollview嵌套listview只显示一行

来源:互联网 发布:广电网络是国企吗 编辑:程序博客网 时间:2024/05/29 08:28
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对应的AdapterExpandableListAdapter listAdapter = listView.getExpandableListAdapter();if (listAdapter == null) {// pre -conditionreturn;}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);}



0 0
原创粉丝点击