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 @Override 16 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 }
在布局文件中使用
1 <com.vaqp.utils.MyGridView 2 android:id="@+id/location_gview" 3 android:layout_width="match_parent" 4 android:layout_height="wrap_content" 5 android:background="#D3D3D3" 6 android:columnWidth="100dp" 7 android:numColumns="auto_fit" 8 android:paddingLeft="10dip" 9 android:verticalSpacing="1dip" > 10 </com.vaqp.utils.MyGridView>
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 = totalHeight 15 + (listView.getDividerHeight() * (listAdapter.getCount() - 1)); 16 listView.setLayoutParams(params); 17 }