-
-
Save brandhill/f8f8d9c92758d8cd194d5cb2692aff67 to your computer and use it in GitHub Desktop.
Set Empty Layout for RecyclerViews in Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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