In RecyclerView, I want to set an empty view to be shown when the adapter is empty. Is there an equivalent of ListView.setEmptyView()?
My version, based on https://gist.github.com/adelnizamutdinov/31c8f054d1af4588dc5c
public class EmptyRecyclerView extends RecyclerView {
@Nullable
private View emptyView;
public EmptyRecyclerView(Context context) { super(context); }
public EmptyRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); }
public EmptyRecyclerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private void checkIfEmpty() {
if (emptyView != null && getAdapter() != null) {
emptyView.setVisibility(getAdapter().getItemCount() > 0 ? GONE : VISIBLE);
}
}
private final AdapterDataObserver observer = new AdapterDataObserver() {
@Override
public void onChanged() {
checkIfEmpty();
}
@Override
public void onItemRangeInserted(int positionStart, int itemCount) {
checkIfEmpty();
}
@Override
public void onItemRangeRemoved(int positionStart, int itemCount) {
checkIfEmpty();
}
};
@Override
public void setAdapter(@Nullable Adapter adapter) {
final Adapter oldAdapter = getAdapter();
if (oldAdapter != null) {
oldAdapter.unregisterAdapterDataObserver(observer);
}
super.setAdapter(adapter);
if (adapter != null) {
adapter.registerAdapterDataObserver(observer);
}
checkIfEmpty();
}
@Override
public void setVisibility(int visibility) {
super.setVisibility(visibility);
if (null != emptyView && (visibility == GONE || visibility == INVISIBLE)) {
emptyView.setVisibility(GONE);
} else {
checkIfEmpty();
}
}
public void setEmptyView(@Nullable View emptyView) {
this.emptyView = emptyView;
checkIfEmpty();
}
}