First off, don’t do it. Secondly, if you need to do it, here’s how:
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.
Great! Thanks you!
Thanks kenneth
Its so helpful to me..Now I m so happy.:)
Great Kenneth!
And, yeah, thank you!
Excellent. Thank you very much!
You save my Day!!! Thank you very much