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
- The layout is a vertically oriented LinearLayout with only two items, the recyclerview and the container for the progressbar.
- The progressbar is the second item in this list.
- 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
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.
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!
Top comments (1)
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
ProgressBar. This approach works great if we are doing pagination.