即动态获取ListView和GridView的高度
一、对于ListView
ListView listview= new ListView(this);
setListViewHeightBasedOnChildren(listview);即可
1 public static void setListViewHeightBasedOnChildren(ListView listView) { 2 // 获取ListView对应的Adapter 3 ListAdapter listAdapter = listView.getAdapter(); 4 if (listAdapter == null) { 5 // pre-condition 6 return; 7 } 8 9 int totalHeight = 0; 10 for (int i = 0, len = listAdapter.getCount(); i < len; i++) { // listAdapter.getCount()返回数据项的数目 11 View listItem = listAdapter.getView(i, null, listView); 12 listItem.measure(0, 0); // 计算子项View 的宽高 13 totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度 14 } 15 16 ViewGroup.LayoutParams params = listView.getLayoutParams(); 17 params.height = totalHeight 18 + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); 19 // listView.getDividerHeight()获取子项间分隔符占用的高度 20 // params.height最后得到整个ListView完整显示需要的高度 21 listView.setLayoutParams(params); 22 }
二、对于GridView
GridView gridview = new GridView(this);
setGridViewHeightBasedOnChildren(gridview );即可
1 public static void setGridViewHeightBasedOnChildren(GridView gridView) { 2 // 获取GridView对应的Adapter 3 ListAdapter listAdapter = gridView.getAdapter(); 4 if (listAdapter == null) { 5 return; 6 } 7 int rows; 8 int columns=0; 9 int horizontalBorderHeight=0; 10 Class<?> clazz=gridView.getClass(); 11 try { 12 //利用反射,取得每行显示的个数 13 Field column=clazz.getDeclaredField("mRequestedNumColumns"); 14 column.setAccessible(true); 15 columns=(Integer)column.get(gridView); 16 //利用反射,取得横向分割线高度 17 Field horizontalSpacing=clazz.getDeclaredField("mRequestedHorizontalSpacing"); 18 horizontalSpacing.setAccessible(true); 19 horizontalBorderHeight=(Integer)horizontalSpacing.get(gridView); 20 } catch (Exception e) { 21 // TODO: handle exception 22 e.printStackTrace(); 23 } 24 //判断数据总数除以每行个数是否整除。不能整除代表有多余,需要加一行 25 if(listAdapter.getCount()%columns>0){ 26 rows=listAdapter.getCount()/columns+1; 27 }else { 28 rows=listAdapter.getCount()/columns; 29 } 30 int totalHeight = 0; 31 for (int i = 0; i < rows; i++) { //只计算每项高度*行数 32 View listItem = listAdapter.getView(i, null, gridView); 33 listItem.measure(0, 0); // 计算子项View 的宽高 34 totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度 35 } 36 ViewGroup.LayoutParams params = gridView.getLayoutParams(); 37 params.height = totalHeight+horizontalBorderHeight*(rows-1);//最后加上分割线总高度 38 gridView.setLayoutParams(params); 39 }
时间: 2024-10-26 09:44:30