Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I put a ListView into a ScrollView without it collapsing?

I've searched around for solutions to this problem, and the only answer I can find seems to be "don't put a ListView into a ScrollView". I have yet to see any real explanation for why though. The only reason I can seem to find is that Google doesn't think you should want to do that. Well I do, so I did.

So the question is, how can you place a ListView into a ScrollView without it collapsing to its minimum height?

like image 360
DougW Avatar asked Aug 16 '10 18:08

DougW


People also ask

What is nested scroll view?

NestedScrollView is just like ScrollView , but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. Nested scrolling is enabled by default.

Is ListView scrollable by default?

ListView itself is scrollable.

What is the difference between ListView and ScrollView?

ScrollView is used to put different or same child views or layouts and the all can be scrolled. ListView is used to put same child view or layout as multiple items. All these items are also scrollable. Simply ScrollView is for both homogeneous and heterogeneous collection.


2 Answers

Here's my solution. I'm fairly new to the Android platform, and I'm sure this is a bit hackish, especially in the part about calling .measure directly, and setting the LayoutParams.height property directly, but it works.

All you have to do is call Utility.setListViewHeightBasedOnChildren(yourListView) and it will be resized to exactly accommodate the height of its items.

public class Utility {     public static void setListViewHeightBasedOnChildren(ListView listView) {         ListAdapter listAdapter = listView.getAdapter();         if (listAdapter == null) {             // pre-condition             return;         }          int totalHeight = listView.getPaddingTop() + listView.getPaddingBottom();          for (int i = 0; i < listAdapter.getCount(); i++) {             View listItem = listAdapter.getView(i, null, listView);             if (listItem instanceof ViewGroup) {                 listItem.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));              }               listItem.measure(0, 0);              totalHeight += listItem.getMeasuredHeight();         }          ViewGroup.LayoutParams params = listView.getLayoutParams();         params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));         listView.setLayoutParams(params);     } } 
like image 105
DougW Avatar answered Oct 09 '22 07:10

DougW


Using a ListView to make it not scroll is extremely expensive and goes against the whole purpose of ListView. You should NOT do this. Just use a LinearLayout instead.

like image 20
Romain Guy Avatar answered Oct 09 '22 07:10

Romain Guy