Skip to content

Instantly share code, notes, and snippets.

@ilguzin
Last active December 12, 2015 04:28
Show Gist options
  • Save ilguzin/4714453 to your computer and use it in GitHub Desktop.
Save ilguzin/4714453 to your computer and use it in GitHub Desktop.
The snippet gives you an ability to set ListView height according to elements number in it, when the ListView is placed inside ScrollView. Stolen from SO.
class HackUtils {
public static void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
// pre-condition
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
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