Skip to content

Instantly share code, notes, and snippets.

@webserveis
Forked from sheharyarn/RVEmptyObserver.java
Last active February 1, 2021 18:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webserveis/7e6f3eb224c709f817b82d9a23441cd3 to your computer and use it in GitHub Desktop.
Save webserveis/7e6f3eb224c709f817b82d9a23441cd3 to your computer and use it in GitHub Desktop.
Set Empty Layout for RecyclerViews in Android
/**
* https://stackoverflow.com/questions/28217436/how-to-show-an-empty-view-with-a-recyclerview
*
* Custom implementation of AdapterDataObserver to show empty layouts
* for RecyclerView when there's no data
*
* Usage:
*
* adapter.registerAdapterDataObserver(new RVEmptyObserver(recyclerView, emptyView));
*/
public class RVEmptyObserver extends RecyclerView.AdapterDataObserver {
private View emptyView;
private RecyclerView recyclerView;
/**
* Constructor to set an Empty View for the RV
*/
public RVEmptyObserver(RecyclerView rv, View ev) {
this.recyclerView = rv;
this.emptyView = ev;
checkIfEmpty();
}
/**
* Check if Layout is empty and show the appropriate view
*/
private void checkIfEmpty() {
if (emptyView != null && recyclerView.getAdapter() != null) {
boolean emptyViewVisible = recyclerView.getAdapter().getItemCount() == 0;
emptyView.setVisibility(emptyViewVisible ? View.VISIBLE : View.GONE);
recyclerView.setVisibility(emptyViewVisible ? View.GONE : View.VISIBLE);
}
}
/**
Abstract method implementations
*/
@Override
public void onChanged() {
checkIfEmpty();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
checkIfEmpty();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
checkIfEmpty();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment