SIr Codealot SIr Codealot - 2 months ago 50
Android Question

Understanding RecyclerView setHasFixedSize

I'm having some trouble understanding

setHasFixedSize()
. I know that it is used for optimization when the size of
RecyclerView
doesn't change, from the docs.

What does that mean though? In most common cases a
ListView
almost always has a fixed size. In what cases would it not be a fixed size? Does it mean that the actual real estate that it occupies on screen grows with the content?

Answer

A very simplified version of RecyclerView has:

void onItemsInsertedOrRemoved() {
   if (hasFixedSize) layoutChildren();
   else requestLayout();
}

This link describes why calling requestLayout might be expensive. Basically whenever items are inserted, moved or removed the size (width and height) of RecyclerView might change and in turn the size of any other view in view hierarchy might change. This is particularly troublesome if items are added or removed frequently.

Avoid unnecessary layout passes by setting setHasFixedSize to true when you are adding or removing items in the RecyclerView and that doesn't change it's height or the width.

Comments