1.第一种方法只能实用单个的listview。第二个是适合ScrollView嵌套listview,然后listview中还可以包含GridView 但是必须自定义listview或则是GridView
public static int setListViewHeightBasedOnChildren(ListView listView){
int scrollViewHight = 0;
int totalHight = 0;
ListAdapter listAdapter = listView.getAdapter();
if(listAdapter == null){
return 0;
}
for(int i = 0; i < listAdapter.getCount(); i++){
View itemView = listAdapter.getView(i, null, listView);
itemView.measure(0, 0);
totalHight += itemView.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
scrollViewHight = totalHight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
params.height = scrollViewHight;
listView.setLayoutParams(params);
return scrollViewHight;
}
2.首先,ListView不能直接用,要自定义一个,然后重写onMeasure()方法:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2, MeasureSpec.AT_MOST); super.onMeasure(widthMeasureSpec, expandSpec); }