Sunday, December 21, 2014

Android RecyclerView - Adding Empty View

So RecyclerView was introduced to replace List view and it's optimized to reuse existing views and so it's faster and more efficient as stated in the documentation:

https://developer.android.com/training/material/lists-cards.html

While using it, I faced the issue of missing a useful functionality that is implemented in ListView.
that feature is setting an empty view in case there was no records.

In ListView it was as simple as this

View emptyView = findViewById(R.id.mylist_empty_view);
ListView  myList = ....
myList.setEmptyView(emptyView);

but this method doesn't exist for recycler view so we need a work around until android team fixes this.


and here are the screen shots of both list view and recycler view fix

List view :

Recycler view :



here is how I fixed it:



here is the content of empty_view, it can be anything.



Enjoy.

3 comments:

  1. Good approach. But why does it still inflate the empty view when the data is loading, and then gone when the data is loaded? Hope you can provide the fix. Thanks for posting!

    ReplyDelete
  2. code error, public RecyclerView.ViewHolder onCreateViewHolder ->return ViewHolder, but EmptyViewHolder evh = new EmptyViewHolder(v);->return EmptyViewHolder

    ReplyDelete
  3. Thank you! Initially I set EMPTY_VIEW == 0, which caused some weird issues. Setting it to 10 made it work as expected.

    ReplyDelete

Note: Only a member of this blog may post a comment.

Istio —simple fast way to start

istio archeticture (source istio.io) I would like to share with you a sample repo to start and help you continue your jou...