1.GidView使用的时候可以先重载GirdView例如:
1 public class MyGridView extends GridView { 2 3 public MyGridView(Context context) { 4 super(context); 5 } 6 7 public MyGridView(Context context, AttributeSet attrs) { 8 super(context, attrs); 9 }10 11 public MyGridView(Context context, AttributeSet attrs, int defStyle) {12 super(context, attrs, defStyle);13 }14 15 @Override16 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {17 18 int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,MeasureSpec.AT_MOST);19 20 super.onMeasure(widthMeasureSpec, expandSpec);21 }22 23 }
在布局文件中使用
110
2.ListView在setAdapter后调用setListViewHeightBasedOnChildren方法:
1 sortListView.setAdapter(adapter); 2 LvHeightUtil.setListViewHeightBasedOnChildren(sortListView);
1 public static void setListViewHeightBasedOnChildren(ListView listView) { 2 ListAdapter listAdapter = listView.getAdapter(); 3 if (listAdapter == null) { 4 return; 5 } 6 int totalHeight = 0; 7 for (int i = 0; i < listAdapter.getCount(); i++) { 8 View listItem = listAdapter.getView(i, null, listView); 9 listItem.measure(0, 0);10 totalHeight += listItem.getMeasuredHeight();11 }12 13 ViewGroup.LayoutParams params = listView.getLayoutParams();14 params.height = totalHeight15 + (listView.getDividerHeight() * (listAdapter.getCount() - 1));16 listView.setLayoutParams(params);17 }