Understanding RecyclerView setHasFixedSize

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 changing the contents of the adapter does not change it’s height or the width.


Update: The JavaDoc has been updated to better describe what the method actually does.

RecyclerView can perform several optimizations if it can know in
advance that RecyclerView’s size is not affected by the adapter
contents. RecyclerView can still change its size based on other
factors (e.g. its parent’s size) but this size calculation cannot
depend on the size of its children or contents of its adapter (except
the number of items in the adapter).

If your use of RecyclerView
falls into this category, set this to {@code true}. It will allow
RecyclerView to avoid invalidating the whole layout when its adapter
contents change.

@param hasFixedSize true if adapter changes cannot affect the size of
the RecyclerView.

Leave a Comment