Limit height of ListView on Android

I solved this problem in code, setting height of listview only if it has more than 5 items in it:

if(adapter.getCount() > 5){
        View item = adapter.getView(0, null, listView);
        item.measure(0, 0);         
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, (int) (5.5 * item.getMeasuredHeight()));
        listView.setLayoutParams(params);
}

Notice that I set the max height to 5.5 times the height of a single item, so the user will know for sure there is some scrolling to do! 🙂

Leave a Comment