Skip to content

Instantly share code, notes, and snippets.

@sanmadjack
Created August 11, 2014 15:04
Show Gist options
  • Save sanmadjack/65b35108abebf0bba3c6 to your computer and use it in GitHub Desktop.
Save sanmadjack/65b35108abebf0bba3c6 to your computer and use it in GitHub Desktop.
Android C# function to resize ListView height to match contents
private void ResizeListViewHeight(ListView lv) {
IListAdapter la = lv.Adapter;
if (la == null) {
return;
}
int totalHeight = 0;
DisplayMetrics dm = new DisplayMetrics();
WindowManager.DefaultDisplay.GetMetrics(dm);
int listViewWidth = dm.WidthPixels;
int widthSpec = View.MeasureSpec.MakeMeasureSpec(listViewWidth, MeasureSpecMode.AtMost);
for(int i = 0; i < la.Count; i++) {
View li = la.GetView(i,null,lv);
li.Measure(widthSpec, View.MeasureSpec.MakeMeasureSpec(0, MeasureSpecMode.Unspecified));
totalHeight += li.MeasuredHeight;
}
ViewGroup.LayoutParams par = lv.LayoutParameters;
par.Height = totalHeight + (lv.DividerHeight * (la.Count - 1));
lv.LayoutParameters = par;
lv.RequestLayout();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment