Skip to content

Instantly share code, notes, and snippets.

@brandhill
Forked from sheharyarn/RVEmptyObserver.java
Created August 16, 2020 13:23
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 brandhill/f8f8d9c92758d8cd194d5cb2692aff67 to your computer and use it in GitHub Desktop.
Save brandhill/f8f8d9c92758d8cd194d5cb2692aff67 to your computer and use it in GitHub Desktop.
Set Empty Layout for RecyclerViews in Android
/**
* 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