Skip to content

Instantly share code, notes, and snippets.

@SehoNoh
Last active August 29, 2015 14:06
Show Gist options
  • Save SehoNoh/5638005fa27763fd21f8 to your computer and use it in GitHub Desktop.
Save SehoNoh/5638005fa27763fd21f8 to your computer and use it in GitHub Desktop.
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
int desiredWidth = MeasureSpec.makeMeasureSpec(listView.getWidth(), MeasureSpec.AT_MOST);
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
listView.requestLayout();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment