SIr Codealot SIr Codealot - 10 months ago 233
Android Question

Understanding RecyclerView setHasFixedSize

I'm having some trouble understanding

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

What does that mean though? In most common cases a
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 Source

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.