EmptyRecyclerView extends RecyclerView { @Override public void setAdapter(Adapter adapter) { final Adapter oldAdapter = getAdapter(); if (oldAdapter != null) { oldAdapter.unregisterAdapterDataObserver(mObserver); } super.setAdapter(adapter); if (adapter != null) { adapter.registerAdapterDataObserver(mObserver); } checkIfEmpty(); } EmptyRecyclerView(Context context);  EmptyRecyclerView(Context context, AttributeSet attrs);  EmptyRecyclerView(Context context, AttributeSet attrs, int defStyle); @Override void setAdapter(Adapter adapter); void setEmptyView(View emptyView);  }
@Test public void should_show_empty_view_if_adapter_is_empty() { RecyclerView.Adapter adapter = new RecyclerView.Adapter() { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { } @Override public int getItemCount() { return 0; } }; recyclerView.setAdapter(adapter); assertThat(emptyView.getVisibility()).isEqualTo(View.VISIBLE); }
@Test public void should_hide_empty_view_if_adapter_has_data() { RecyclerView.Adapter adapter = new RecyclerView.Adapter() { @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { } @Override public int getItemCount() { return 2; } }; recyclerView.setAdapter(adapter); assertThat(emptyView.getVisibility()).isEqualTo(View.GONE); }