Leonardo Dias Leonardo Dias - 12 days ago 8
Android Question

RecyclerView inside a ScrollView

I always worked with

ListView
, and within a
ScrollView
I used the
setListViewHeightBasedOnItems
method to set the height according to the number of items in the list.

Now i'm working with
RecyclerView
, however this method to set the height does not work anymore, what should i do to use
RecyclerView
within a
ScrollView
?

Answer

One of the great things about RecyclerView is that it makes it a little more clear when either a ListView or a RecyclerView is not an appropriate widget to use in a given situation.

RecyclerView is designed to recycle Views that are not on screen to make scrolling more efficient. If you want a container for a group of Views to have a height equal to the height of all of its children, then each of its children must first be laid out and measured. One View for each item must be inflated, thus defeating the purpose of allowing Views to be recycled in the first place.

Instead, you may want to look into using a simple LinearLayout for this purpose. You can still use an Adapter to populate the View, and you will get the behavior you want out of the box. If you want to use an adapter to populate a LinearLayout, your code might look something like this:

LinearLayout container = (LinearLayout) findViewById(R.id.list_container);
Adapter listAdapter = createListAdapter();

final int childCount = listAdapter.getCount();
for (int i = 0; i < childCount; i++) {
    View child = listAdapter.getView(i, null, container);
    container.addView(child);
}
Comments