DEV Community

Aniket Kadam
Aniket Kadam

Posted on

The Simplest Recycler EmptyView

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!

Oldest comments (1)

Collapse
 
burhanrashid52 profile image
Burhanuddin Rashid

This won't work properly if the item-count is small, let say 2-3, which leaves space in the bottom. At that time we will see both the RecycleView and the ProgressBar. This approach works great if we are doing pagination.