Skip to content

Instantly share code, notes, and snippets.

@dokkaebi
Created November 30, 2012 02:39
Show Gist options
  • Save dokkaebi/4173446 to your computer and use it in GitHub Desktop.
Save dokkaebi/4173446 to your computer and use it in GitHub Desktop.
Android: Set listview item heights to fill available listview height.
public class MyAdapter extends SimpleCursorAdapter {
// constructor, etc...
@Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
// Stretch list item height if there are too few to fill the content area.
ListView listView = getListView();
int listViewHeight = listView.getMeasuredHeight();
int itemCount = cursor.getCount();
int itemHeight = view.getMeasuredHeight();
int dividerHeight = listView.getDividerHeight();
int totalDividerHeight = (itemCount - 1) * dividerHeight;
int targetTotalItemHeight = listViewHeight - totalDividerHeight;
int totalItemHeight = itemCount * itemHeight;
boolean weNeedToUpsize = totalItemHeight < targetTotalItemHeight;
if (weNeedToUpsize) {
int targetItemHeight = targetTotalItemHeight / itemCount;
view.setMinimumHeight(targetItemHeight);
}
}
}
@samskiter
Copy link

does this continue to work if you add more items to the listview?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment