Understanding RecyclerView setHasFixedSize

Issue

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?

Solution

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.

Answered By – LukaCiko

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published