Putting Android ListViews in ScrollViews

First off, don’t do it.  Secondly, if you need to do it, here’s how:

StackOverflow

The key bit of code is this:

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);
        listView.requestLayout();
    }

borrowed from Java2S.

Frankly, the only use case I can imagine for this is the one described in the StackOverflow question.  It just turns out that I had that exact problem tonight.  There are a large number of reasons why this is a bad idea in general, but in a very narrow set of use cases it can be what you want.

5 thoughts on “Putting Android ListViews in ScrollViews

Leave a comment