ListView inside ScrollView. Solve the problem.

Oleg Skidan
2 min readFeb 5, 2016

--

Picture from android.amberfog.com

Many Android developers faced with the challenge of showing all elements of ListView inside ScrollView.

The problem is that usually shows only one element.

The second problem is a redrawing ListView when added to it (or removed from) the other element. In this case, also just one element is shown.

Of course, the user will want to see the whole list, but not a single element.

Today we will solve this problem. I could not find an answer in the official documentation.

After collecting a certain number of answers to stackoverflow.com, I chose the most successful solution, which I will explain in detail.

We need to create a method:

public static void setListViewHeightBasedOnChildren
(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();if (listAdapter == null) return;int desiredWidth = easureSpec.makeMeasureSpec(listView.getWidth(),
MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0) view.setLayoutParams(new
ViewGroup.LayoutParams(desiredWidth,
LayoutParams.WRAP_CONTENT));

view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}


ViewGroup.LayoutParams params = listView.getLayoutParams();

params.height = totalHeight + (listView.getDividerHeight() *
(listAdapter.getCount() — 1));

listView.setLayoutParams(params);
listView.requestLayout();
}

This method we need to call (passing in our ListView) after we have assigned for the ListView adapter. It is important to understand that with any change in the data in the ListView (adding or removing) we need to use this method again. Next, I will explain why.

Usually, I use this method after calling notifyDataSetChanged () on the adapter.

It works on API 7+ (checked). Let me explain what’s happening here.

First, we check whether there is our ListView adapter — if not, leave. The main action takes place in a loop, where we go through each element and increase the maximum height for our ListView (highlighted in the code).

After this update the height for our ListView.

Now, ListView takes as much space as it need. Do not forget to use this method, after the change of elements in the ListView.

Kind regards.

--

--