Skip to content

Instantly share code, notes, and snippets.

@ajamaica
Created April 6, 2015 19:51
Show Gist options
  • Save ajamaica/8d6ba913c94c604b6900 to your computer and use it in GitHub Desktop.
Save ajamaica/8d6ba913c94c604b6900 to your computer and use it in GitHub Desktop.
setListViewHeightBasedOnChildren
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
if (listItem instanceof ViewGroup) {
listItem.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
}
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment