public class ListViewRelayout {
public void setListViewHeightBasedOnChildren(ListView listView) {
// get the list view adapter, so this function must be invoked after set the adapter.
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
// get the ListView count
int count = listAdapter.getCount();
for (int i = 0; i < count; i++) {
View listItem = listAdapter.getView(i, null, listView);
// measure the child view
listItem.measure(0, 0);
// calculate the total height of items
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
// get divider height for all items and add the total height
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
}
2、在ListActivity.java mAppListView.setAdapter(mAppListAdapter);
mRelayout.setListViewHeightBasedOnChildren(mAppListView);
如果你还增加了对ListView的动态改变,那么,还需要在notifyDataSetChanged后再调用一次,如:
mEnableAppListAdapter.notifyDataSetChanged();
mUtil.setListViewHeightBasedOnChildren(mEnableAppListView);