1.listview解决方法
public static void setListViewHeightBasedOnChildren(ListView listView) { if(listView == null) return; 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);}
2.gridview解决方法
public static void setGridViewHeightBasedOnChildren(GridView gridView){ // 获取listview的adapter ListAdapter listAdapter = gridView.getAdapter(); if (listAdapter == null) { return; } // 固定列宽,有多少列 int col = 3; //gridView.getNumColumns(); int totalHeight = 0; // i每次加4,相当于listAdapter.getCount()小于等于4时 循环一次,计算一次item的高度, // listAdapter.getCount()小于等于8时计算两次高度相加 for (int i = 0; i < listAdapter.getCount(); i += col) { // 获取listview的每一个item View listItem = listAdapter.getView(i, null, gridView); listItem.measure(0, 0); // 获取item的高度和 totalHeight += listItem.getMeasuredHeight(); } // 获取listview的布局参数 ViewGroup.LayoutParams params = gridView.getLayoutParams(); // 设置高度 params.height = totalHeight+20; // 设置margin ((ViewGroup.MarginLayoutParams) params).setMargins(10, 10, 10, 10); // 设置参数 gridView.setLayoutParams(params); }
3.自定义ListView
public class CustomListView extends ListView { public CustomListView(Context context) { super(context); } public CustomListView(Context context, AttributeSet attrs) { super(context, attrs); } public CustomListView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); }}