loading...

The Simplest Recycler EmptyView

aniketsmk profile image Aniket Kadam ・1 min read

A recyclerview with something to show when it's empty is a pretty common pattern, many times we're tempted to do this in code.

We're going to look at a better way to do than:
Checking if the number of items in the adapter is zero and then show the empty view else, show the recyclerview.

Here's the code, and it's all XML

No code required. This will show the recyclerview when items are present, and the progressbar in the center when it's not.

How does it work?

A few key points

  1. The layout is a vertically oriented LinearLayout with only two items, the recyclerview and the container for the progressbar.
  2. The progressbar is the second item in this list.
  3. Recyclerview's widths and heights are always calculated from their children. If there are no children, it sets itself to zero. When there are children, it actually follows the rest of the rules given to it like match_parent

If you look into the source code of the RecyclerView you'd see this line in onMeasure, which is what defines the dimens of the view.

mLayout.setMeasuredDimensionFromChildren(widthSpec, heightSpec);

So that's it! You can now get a clean empty view that naturally gets shoved under the recyclerview when there are items and you didn't one bit of Java/Kotlin code to do it yourself!

Posted on by:

aniketsmk profile

Aniket Kadam

@aniketsmk

An android dev with ~8 years of experience. I consult and may join fulltime for the right company.

Discussion

markdown guide